1、获取长度:
String str = "i am a student.";
int str1=str.length();
2、输入下标,返回字符
String str = "i am a student.";//主串
char c = str.charAt(2);
System.out.println(c);//返回字符a
3、查看某字符是否存在
String str = "i am a student.";//主串
boolean b = str.contains("a"); //子串
System.out.println(b);//是否存在该字符
4、输入某字符,返回下标
String str = "i am a student.";//主串
int index = str.indexOf("a");
System.out.println(index); //返回下标
5、大小写字母的互换
String str = "abc";
String str2 = str.toUpperCase(); //小写转大写
String str3 = str.toLowerCase(); // 大写转小写
System.out.println(str2);
System.out.println(str3);
6、字符串的比较
String str1 = new String("abc");
String str2 = new String("ABC");
int a = str1.compareTo(str2);//a=32
int b = str1.compareToIgnoreCase(str2);//b=0
boolean c = str1.equals(str2);//c=false
boolean d =str1.equalsIgnoreCase(str2);//d=true
7、删除字符串中的空格字符
String str = new String(" 123").intern(); //1
String str1 = str.replaceAll(" ","");
System.out.println(str1);
String str2 = new String("123 "); //2
String str3 = str2.replaceAll(" +","");
System.out.println(str3);
8、将字符串变成一个byte数组
private String str = "i am a student.";
byte b[] = str.getBytes();
System.out.println("转换成byte数组输出为:" + new String(b));
9、String类中常见的一些问题
String srt1 = “hello”;
String str2 = “hello”;//str1 == str2;返回值为true,指向的是同一个地址。
String srt1 = new String(“hello”);
String str2 = new String(“hello”);//str1 == str2;
返回值为false,指向的是不同的地址。
此时应使用System.out.println(str1.equals(str2));
//String srt1 = new String(“hello”).intern();
String str2 = new String(“hello”);
str1 == str2;//此时返回的也为true;
String srt1 = “helloworld”;
String str2 = “hello”+”world”;//直接优化为helloworld,所以和str1地址一样 System.out.println(str1 == str2);//此时返回的是true;
String srt = “helloworld”;
String str2 = “hello”;
String str2 = str2+”world”;
//new StringBuilder();
//s.append(“hello”);
//s.append(“world”);
//s.toString(); StringBuilder->String;
System.out.println(str == str3);
//地址不同,所以此时返回的是false;