java中的String类的常用方法

java中的String类包含了50多种方法,今天我们来介绍一部分最常用的方法

1.获取长度  

int length();

例:

      String str="hello";

       int n=str.length();    输出得到 5

2.根据位置获取位置上的某个字符 

 char charAt(int index);

例:

    String str="hello";

    char ch=str.charAt(3);  输出得到 l

3.返回字符串或者代码点第一次出现的位置

  int indexOf(String str);

  int indexOf(int cp);

 不存在则返回-1

例:

    String str="hello";

   int n=str.indexOf('l'); 输出得到 2

  int m=str.indexOf('w'); 输出得到 -1

4从指定位置开始,返回字符串或者代码点第一次出现的位置  

int indexOf(String str,int fromIndex);

int indexOf(int cp,int fromIndex);

不存在返回-1

例:

String str="hello";

int n=str.indexOf('l',3); 输出得到 3

int m=str.indexOf('s',3); 输出得到 -1

5.字符串中是否包含一个子串

boolean contain(String str);

例:

String str="hello";

boolean b=str.contain('lo');输出得到 true

6.字符串中是否有内容

boolean isEmpty();

例:

String str="hello";

boolean b=str.isEmpty(); 输出得到false

7.字符串是否是以指定内容开头

boolean startsWith(String str);

例:

String str="hello";

boolean b=str.stratsWith('he'); 输出得到true

8.字符串是否是以指定内容结尾

boolean endsWith(String str);

例:

String str="hello";

boolean b=str.endsWith('s'); 输出得到false

9.字符串是否相等

boolean equals(String str);

例子:

String str="hello";

boolean b=str.equals('what'); 输出得到false

10.将字符串数组转换为字符串

构造方法 String(char[] arr);

部分转化String(char[] arr,int start,int cout)    start起始位,count个数

例子:

char[] arr={'h','e','l','l','o',};

String str=new String(arr); 输出得到 hello

11.讲字符串转换成字符数组 char[] tocharArray();

例:

String str="hello";

char[] arr=str.tocharArray();输出得到hello字符

12.替换

String replace( oldchar, newchar);

如果替换的字符不存在,则返回原串

例;

String str="hello";

String s=str.replace('l','s'); 输出得到 hesso

String ss=str.replace(''si","bo"); 输出得到hello

13.切割

String[] split(String str);

例:

String str="hello,world";

String [] s=str.split(","); 输出得到hello world

14.返回原串的大(小)写

String toLowerCase();

String toUpperCase();

例:

String str="hello";

String s=str.toUpperCase(); 输出得到HELLO

15.获取字符串中的一部分

String substring(int begin);

String substring(int begin int end);包头不包尾

例:

String str="hello";

String s=str.substring(2); 输出得到 l 

String s=str.substring(2,4);输出得到 ll

16.返回一个新字符串,这个字符串删除了原始字符串开头和结尾的空格

String trim();

例:
String str="    hello    ";

String s=str.trim();   输出得到 hello


                                                         

猜你喜欢

转载自blog.csdn.net/chengge1124/article/details/53927959