操作字符串的常用方法:
public class StringMethodsExample {
public static void main(String[] args) {
String originalString = "hello,my name is Jack,I am 18 years!";
System.out.println("原始字符串为:\""+ originalString + "\"");
String[] splitedString = originalString.split(","); //使用逗号分割符拆分字符串
System.out.println("按逗号(,)分割以后的字符串数组元素为:");
for(int i=0;i<splitedString.length;i++){ //循环输出拆分后的字符串中的元素
System.out.print("[" + splitedString[i] + "]");
}
System.out.println();
splitedString = originalString.split("m"); //使用字符'm'拆分字符串
System.out.println("按字母'm'分割以后的字符串数组元素为:");
for(int i=0;i<splitedString.length;i++){ //循环输出拆分后的字符串中的元素
System.out.println("[" + splitedString[i] + "]");
}
System.out.println();
System.out.print("原始字符串从第2个到第5个的字符串为:");
System.out.println("\"" + originalString.subSequence(2,6) + "\""); //输出字符串
System.out.print("原始字符串转换成大写字母以后:");
System.out.println("\"" + originalString.toUpperCase() + "\""); //将字符串全部转换为大写
System.out.print("原始字符串转换为小写字母以后:");
System.out.println("\"" + originalString.toLowerCase() + "\""); //将字符串全部转换成小写
}
}
编译并运行后输出的结果为:
原始字符串为:"hello,my name is Jack,I am 18 years!"
按逗号(,)分隔以后的字符串数组元素为:[hello][my name is Jack][I am 18 years!]
按字母'm'分隔以后的字符串数组元素为:[hello,] [y na][e is Jack,I a] [ 18 years!]
原始字符串从第 2 个到第 5 个的字符序列为:"llo,"
原始字符串转换为大写字母以后:"HELLO,MY NAME IS JACK,I AM 18 YEARS!"
原始字符串转换为小写字母以后:"hello,my name is jack,i am 18 years!"