基本操作
String s1 = "Hello World";
String s2 = new String("Hello World");
StringBuilder sb = new StringBuilder();
sb.append('h');
sb.append('e');
sb.append('l');
sb.append('l');
sb.append('o');
String s4 = sb.toString();
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append('h')
.append('e')
.append('l')
.append('l')
.append('o')
.append(' ')
.append("world");
String s5 = stringBuffer.toString();
int length1 = s1.length();
System.out.println("The length of s1:" + length1);
System.out.println("The length of s2:" + s2.length());
- 获取特定位置字符:index取值范围:[0, length - 1],不要越界
char ch1 = s2.charAt(0)
System.out.println("index 0 of s2:" + ch1)
char ch2 = s2.charAt(10)
System.out.println("index 10 of s2:" + ch2)
// 遍历字符串
for (int i = 0
System.out.println("ch in s2:" + s2.charAt(i))
}
// 用+连接
String str1 = s1 + s2
System.out.println("Str1:" + str1)
// concat函数(方法)
String str2 = s1.concat(s2)
String str3 = s2.concat(s1)
String str4 = s1.concat(s2).concat(s3).concat(s4)
System.out.println("Str2:" + str2)
System.out.println("Str3:" + str3)
System.out.println("Str4:" + str4)
// 方法一
String formatS = String.format("int value: %d, float value: %f, " +
"2 bit double value: %.2f, " +
"string value: %s", 100, 3.1415f, 1.23456, "java");
System.out.println("s after formatting: " + formatS);
// 方法二
System.out.printf("SOUF: %s %s", s1, s2);
// String -> Numeric: 用包装类的parseXXX
int intNum = Integer.parseInt("100")
long longNum = Long.parseLong("1000000")
double doubleNum = Double.parseDouble("3.1415")
System.out.printf("int num: %d\n", intNum)
System.out.printf("long num: %d\n", longNum)
System.out.printf("double num: %.2f\n", doubleNum)
// Numeric -> String
String numberStr1 = 100 + ""
System.out.println(numberStr1)
String numberStr2 = String.valueOf(1.618)
System.out.println(numberStr2)
String numberStr3 = String.valueOf(1000)
System.out.println(numberStr3)
System.out.println(s5.isEmpty());
System.out.println(new String().isEmpty());
System.out.println(s1.equals(s2));
System.out.println(s3.indexOf('L'));
System.out.println(s3.lastIndexOf('L'));
System.out.println(s3.toLowerCase());
System.out.println(s4.toUpperCase());
System.out.println(s1.substring(0, 3));
String st = " Hello ";
System.out.println(st.trim());