Java常用类之String常用方法(一)

String常用方法:
1.int length();返回字符串的长度
例子:

		String s1 ="HelloWorld";
		System.out.println(s1.length());

运行结果:

10

2.char charAt(int index);返回某索引处的字符
例子:

		String s1 ="HelloWorld";
		System.out.println(s1.charAt(0));//返回索引处的数值
		System.out.println(s1.charAt(9));

运行结果:

H
d

3.boolean isEmpty();判断是否是空字符串
例子:

String s1 ="HelloWorld";
System.out.println(s1.isEmpty());
s1 = "";
System.out.println(s1.isEmpty());

运行结果:
false
true

4.String toLowerCase();将String中的所有字符转换为小写
String toUpperCase();将String中的所有字符转换为大写

例子:

		String s1 ="HelloWorld";
		String s2 = s1.toLowerCase();//把字母变成小写
		System.out.println(s1);//s1是不可变的,仍然是原来的值
		System.out.println(s2);
		String s0 = s1.toUpperCase();//把字母变成大写
		System.out.println(s0);

运行结果:

HelloWorld
helloworld
HELLOWORLD	

5.String trim();去掉字符串首尾的空格
例子:

		String s3 = "    he  llo  world    ";
		String s4 = s3.trim();//去除字符串首尾的空格
		System.out.println("-----"+ s3 +"-----");
		System.out.println("-----"+ s4 +"-----");

运行结果:

-----    he  llo  world    -----
-----he  llo  world-----
boolean equals(Object obj)比较字符串的内容是否相同
boolean equalsIgnoreCase(String anotherString) 比较内容是否相同且忽略大小写

PS:String类中的equals()方法是被重写过的,即:只有在String类及少数类中equals()方法比较的是内容,大部分其他类中equals()方法比的是地址值是否相同。另外,“==”比的也是地址值,但在String类中,每个常量只能存在一个,比如说

		String a1 = "abc";
		String a2 = "abc";

其中a1与a2的地址值是相同的,因为String类比较特殊,它有一个常量池,该池中相同的常量只能有一个,所以我们在给a2赋值的时候系统就会自动地把常量池中已有的“abc”的地址赋给a2。具体原理可以看我另一篇文章String字符串是如何储存的

例子:

		String s1 = "HelloWorld";
		String s2 = "helloworld";
		System.out.println(s1.equals(s2));//注意equals比较的是内容,String类的equals经过重写了
		System.out.println(s1.equalsIgnoreCase(s2));//比较内容时忽略大小写

运行结果:

false
true

7.String concat(String str) 将指定字符串连接到此字符串的结尾。
例子:

		String s3 = "abc";
		String s4 = s3.concat("def");//连接字符串
		System.out.println(s4);

运行结果:

abcdef

8.int compareTo(String anotherString) 按字典顺序比较两个字符串。
例子:

		String s5 = "abc";//a是97,b 98,c99 ,d100,e101
		String s6 = new String("abe");
		System.out.println(s5.compareTo(s6));//比较两个字符串的大小,若不相等,则两个字母相减。这里就相当于c-e=99-101=-2
		//结果是负数则说明当前对象小,0就是相等

运行结果:

-2
String substring(int beginIndex) 
          返回一个新的字符串,它是此字符串的一个子字符串。 
String substring(int beginIndex, int endIndex) 
          返回一个新字符串,它是此字符串的一个子字符串。 

String substring(int start,int end),返回的规则是含头不含尾。左闭右开[start,end)。

例子:

		String s7 = "欢迎阅读Tshaxz的学习笔记";
		String s8 = s7.substring(2);//从2开始(第三个字阅,因为是从0开始算的)截取后面的字符串
		System.out.println(s7);
		System.out.println(s8);
		
		String s9 = s7.substring(2,10);
		System.out.println(s9);
		

运行结果:

欢迎阅读Tshaxz的学习笔记
阅读Tshaxz的学习笔记
阅读Tshaxz

你可能感兴趣的:(Java常用类之String常用方法(一))