调用字符串的几种方法

String s="hello world"; 

1、长度              

  System.out.println(s.length());    结果:11(空格也算一个字符)

2、字符串索引位置的字符(单个字符)  

 System.out.println(s.charAt(4));    结果:o


3、提取子串              

  System.out.println(s.substring(2, 8));//包括索引为2 的字符,不包括索引为8 的字      结果:llo wor

4、拆分                

  String[] aaa=s.split(" ");//按空格将字符串分组,并保存成字符串型数组  for(int i=0;i<aaa.length;i++)                                                                                                                                                            { System.out.println(aaa[i]); }    结果:hello world

5、合并                  

 System.out.println(s.concat("Hello!"));      结果:hello worldHello  (在数组结尾加上***)


6、转换成字符数组              

char[] tt= s.toCharArray();
/*将字符变成字符数组,字符串(字符串类对象)只是调用了将字符变成字符数组的方法,
用一个字符将保存的字符数组一行一行输出来*/
for(int i=0;i<tt.length;i++) {
System.out.println(tt[i]);
}             输出结果:

  h

  e

  l

  l

  o

   

  w

  o

  r

  l

  d


7、字符数组转换成字符串

String ss=new String(tt);


9、替换

String string="We are happy!";

System.out.println(string.replaceAll(" ", "6"));//讲所有空格 用"6"代替

结果We6are6happy

11、根据字符找索引位置

System.out.println(string.indexOf('r',3));//11、从第三个字符开始匹配字符为d的字符串的索引位置

结果:are
12、去除字符串前后空格

String ttt=" Laurence is a good man ";

System.out.println(ttt.trim());

结果Laurenceisagoodman 

13、把字符串改成大写

System.out.println(ttt.toUpperCase());


14、把字符串改成小写

System.out.println(ttt.toLowerCase());
15、把字符串改成字节数组表示

byte [] a=ttt.getBytes();
16、根据字节数组生成字符串
System.out.println(new String(a));

原文地址:https://www.cnblogs.com/pkq521/p/13339905.html