当前位置:  首页>> 技术小册>> Java语言基础9-常用API和常见算法

1.5.1 构造方法

● 初始化新创建的 String 对象,表示空字符序列:

  1. public String(){}

初始化一个新创建的 String 对象,使其表示一个和参数相同的字符序列;换言之,新创建的字符串是该参数字符串的副本

  1. public String(String original){}

通过当前参数中的字符数组来构造新的 String :

  1. public String(char[] value){}

通过字符数组的一部分来构造新的 String :

  1. public String(char[] value,int offset, int count){}

通过使用平台的默认字符集解码当前参数中的字节数组来构造新的 String :

  1. public String(byte[] bytes){}

通过使用指定的字符集解码当前参数中的字节数组来构造新的 String :

  1. public String(byte[] bytes,String charsetName){}

示例:

  1. package com.github.string.demo4;
  2. import java.io.UnsupportedEncodingException;
  3. /**
  4. * @author maxiaoke.com
  5. * @version 1.0
  6. */
  7. public class Test {
  8. public static void main(String[] args) throws UnsupportedEncodingException {
  9. // 字符串常量对象
  10. String str = "hello";
  11. System.out.println("str = " + str);
  12. // 无参构造
  13. String str1 = "";
  14. System.out.println("str1 = " + str1);
  15. // 创建"hello"字符串常量的副本
  16. String str2 = new String("hello");
  17. System.out.println("str2 = " + str2);
  18. // 通过字符数组创建
  19. char[] chs = {'a', 'b', 'c', 'd'};
  20. String str3 = new String(chs);
  21. String str4 = new String(chs, 0, 3);
  22. System.out.println("str3 = " + str3);
  23. System.out.println("str4 = " + str4);
  24. // 通过字节数组构造
  25. byte bytes[] = {97, 98, 99 };
  26. String str5 = new String(bytes);
  27. String str6 = new String(bytes,"utf-8");
  28. System.out.println("str5 = " + str5);
  29. System.out.println("str6 = " + str6);
  30. }
  31. }

1.5.2 静态方法

● 返回指定数组的 String :

  1. public static String valueOf(char data[]) {}

返回指定数组的 String(指定子数组的开始索引和子数组的长度):

  1. public static String valueOf(char data[], int offset, int count){}

返回各种类型的 value 的 String :

  1. public static String valueOf(xx value) {}

示例:

  1. package com.github.string.demo5;
  2. /**
  3. * String的静态方法
  4. *
  5. * @author maxiaoke.com
  6. * @version 1.0
  7. */
  8. public class Test {
  9. public static void main(String[] args) {
  10. char[] chs = {'A', 'B', '我', '是', '谁'};
  11. String s = String.valueOf(chs);
  12. System.out.println("s = " + s);
  13. String s1 = String.valueOf(chs, 0, 2);
  14. System.out.println("s1 = " + s1);
  15. Object obj = "你好啊";
  16. String s2 = String.valueOf(obj);
  17. System.out.println("s2 = " + s2);
  18. }
  19. }

1.5.3 使用 “” +

● 任意数据类型和 “字符串” 进行拼接,结果都是字符串。

● 示例

  1. package com.github.string.demo6;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. /**
  5. * @author maxiaoke.com
  6. * @version 1.0
  7. */
  8. public class Test {
  9. public static void main(String[] args) {
  10. int num = 123456;
  11. String s = num + "";
  12. System.out.println("s = " + s);
  13. List<Integer> list = new ArrayList<>();
  14. list.add(1);
  15. list.add(2);
  16. String str = list + "";
  17. System.out.println(str);
  18. }
  19. }

该分类下的相关小册推荐: