直接上代码:
package javaStudy;
public class StringTest {
public static void main(String[] args) {
/**
* 1. 创建字符串;
* 2. 遍历字符串;
* 3. 字符串连接;
* 4. 字符串与数字间转换
* 5. 常用方法;
*
*/
//##############1. 创建字符串 ##############
//1.1 直接赋值
String str1 = "Hello World"; //常量池
String str2 = "Hello World"; //常量池
System.out.println(str1 == str2); //true
//1.2 通过实例化一串字符来创建
String str3 = new String("Hello World"); //引用类型,堆内存中
System.out.println(str1 == str3); //false
//1.3 通过引用字符数组来创建字符串
char[] a = {'A', 'b', 'c', 'E'};
String str4 = new String(a);
//1.4 通过截取字符数组的一部分来创建字符串
char[] a2 = {'a', 'b', 'c', 'D', '6', 'p'};
String str5 = new String(a2, 2, 4); //从index为2的元素开始,向后取4个
//System.out.println(str5);
//##############2. 遍历字符串 ##############
//2.1 通过length()和charAt()方法
for(int i = 0; i < str1.length(); i++) {
//System.out.println(str1.charAt(i));
}
//2.2 通过length()和substring(i ,i+1)方法
for(int i = 0; i < str1.length(); i++) {
//System.out.println(str1.substring(i, i + 1));
}
//2.3 通过toCharArray()方法
char[] c = str1.toCharArray();
for(int i = 0; i < c.length; i++) {
//System.out.println(c[i]);
}
//##############3. 字符串连接 ##############
//3.1 使用'+'
String s1 = "a" + "b";
String s2 = s1 + "c";
//3.2 使用concat()函数
String s3 = s1.concat("d");
String s4 = "abd";
//System.out.println(s3 == s4); //false, s3为引用类型
//System.out.println(s3.equals(s4));
//3.3 使用append()函数
String s5 = new StringBuffer("abc").append("d").toString();
//System.out.println(s5.equals("abcd"));
//##############4. 字符串与数字间转换 ##############
//4.1 String -> Integer
int n = Integer.valueOf("7");
int m = Integer.parseInt("7");
//System.out.println(m);
//4.2 String -> Double
double d1 = Double.valueOf("3.14");
double d2 = Double.parseDouble("3.14");
//System.out.println(d1);
//4.3 Number -> String
String ss = "" + 12;
String ss1 = String.valueOf(12);
//##############5. 常用方法 ##############
//5.1 char charAt(int index)
//5.2 int compareTo(String anotherString)
//5.3 int compareToIgnoreCase(String str)
//5.4 boolean equalsIgnoreCase(String anotherString)
//5.5 boolean equals(Object anObject)
//5.6 String concat(String str)
//5.7 int indexOf(String str)
//5.8 int lastIndexOf(String str)
//5.9 int length()
//5.91 String[] split(String regex)
String ss3 = "You are beautiful";
String[] ss31 = ss3.split(" "); //用空格分隔成多个字串串
//for(String str: ss31)
//System.out.println(str);
//5.92 String substring(int beginIndex, int endIndex)
//5.93 String toLowerCase()
//5.94 String toUpperCase()
//5.95 String trim()
//5.96 static String valueOf(primitive data type x)
}
}