String类
赋值 .length()方法只有字符串有
String s = new String();
s = "HelloWorld";
System.out.println(s.length());
String s1 = "Hello World";
System.out.println(s1.length());
String s2 = new String("Hello World");
System.out.println(s2.length());
.equals()方法
// == 比较地址 new 出新地址 S5 S6不等
String s3 = "123";
String s4 = "123";
System.out.println(s3 == s4); //结果为true
String s5 = new String("1234");
String s6 = new String("1234");
System.out.println(s5 == s6); //结果为false
// .equals() 比较内部内容
System.out.println(s5.equals(s6)); //结果为true
//.equalsIgnoreCase() 忽略大小写
String s7 = "tom";
String s8 = "Tom";
System.out.println(s7.equals(s8)); //false
System.out.println(s7.equalsIgnoreCase(s8)); //true .equalsIgnoreCase()大小写转换
String s70 = s7.toUpperCase();
String s80 = s8.toUpperCase();
System.out.println(s70.equals(s80));//true .toUpperCase()转换为大写
//.concat()方法 字符串连接
String s = new String("你好, ");
String name = new String("张三!");
String sentence = s.concat(name);
System.out.println(sentence);
//.indexOf() 查找第一个字符,字符串的位置 从前往后数
String str = "qwerqwer";
int index = str.indexOf('w');
System.out.println(index); //结果为1
int index2 = str.indexOf("wer");
System.out.println(index2); //结果为1
//.lastIndexOf()查找最后一个字符 字符串的位置
int index3 = str.lastIndexOf('w');
System.out.println(index3); //结果为5
int index4 = str.lastIndexOf("we");
System.out.println(index4); //结果为5
int index4 = str.lastIndexOf("a");
System.out.println(index4); //没找到a,返回-1
//.substring(index)用索引截取字符串
String subStr = str.substring(4);
System.out.println(subStr); //结果为qwer
String str2 = "I LOVE CODE";
String subStr2 = str2.substring(2,6); //截取2之后的包括2;截取6之前的不包括6
System.out.println(subStr2); //结果为LOVE
//.trim(),去掉字符串的开始和结尾的空格
String str3 = " I LOVE CODE ";
System.out.println(str3); //结果 I LOVE CODE
String subStr3 = str3.trim();
System.out.println(subStr3); //结果I LOVE CODE
System.out.println(str3.lastIndexOf("CODE")); //结果,int型索引
System.out.println(str3.startsWith(" I")); //结果true,判断开始
System.out.println(str3.endsWith("CODE")); //结果false,判断结尾
Scanner input = new Scanner(System.in); System.out.println("请输入金额"); String nums = input.next(); StringBuffer str =new StringBuffer(nums); for(int i = str.length()-3; i > 0 ; i-=3){ str.insert(i, ','); } System.out.println(str);
String str = "长亭外.古道边.芳草碧连天.晚风扶.柳笛声残.夕阳山外山"; /*Scanner input = new Scanner(System.in); System.out.println("输入数据"); String str = input.nextLine();*/ String[] arr = str.split("\\."); //遇到特殊字符. 需要\\.转义字符 for( int i = 0 ; i < arr.length; i++){ System.out.println(arr[i]); }