1 获取字符串长度(length())

● public int length():返回此字符串的长度

String s = "helloworld";
System.out.println(s.length());
  • 1.
  • 2.
10
  • 1.

2 连接字符串(concat(String str))

● public String concat(String str):将指定字符串连接到该字符串末尾,返回新字符串

String s1 = "hello";
String s2 = s1.concat("world");
System.out.println(s2);
  • 1.
  • 2.
  • 3.
helloworld
  • 1.

3 获取指定索引处的字符(charAt(int index))

● public char charAt(int index):返回指定索引处的char值

String s = "helloworld";
System.out.println(s.charAt(0));
System.out.println(s.charAt(2));
  • 1.
  • 2.
  • 3.
h
l
  • 1.
  • 2.

4 获取指定字符串第一次出现在该字符串的位置(indexOf(String str))

● public int indexOf(String str):返回指定字符串第一次出现在该字符串内的位置,并返回

String s = "helloworld";
System.out.println(s.indexOf("h"));
System.out.println(s.indexOf("wor"));
  • 1.
  • 2.
  • 3.
0
5
  • 1.
  • 2.

5 截取字符串(substring(int beginIndex, int endIndex))

public String substring(int beginIndex):返回一个字符串,从beginIndex开始截取字符串到字符串结尾

public String substring(int beginIndex, int endIndex):返回一个字符串,从beginIndex到endIndex截取字符串,左闭右开,包含你beginIndex,不包含endIndex

String s = "helloworld";
System.out.println(s.substring(1));
System.out.println(s.substring(1,3));
  • 1.
  • 2.
  • 3.
elloword
el
  • 1.
  • 2.

6 将字符串转换成字符数组(toCharArray())

● public char[] toCharArray():将字符串转换成一个字符数组并返回

String s = "helloworld";
char[] chs = s.toCharArray();
for(int i=0;i<chs.length;i++) {
    System.out.print(chs[i]);
    System.out.print('#');
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
h#e#l#l#o#w#o#r#l#d#
  • 1.

7 将char[]/char/int/double等转换成字符串(valueOf(char[] data)/valueOf(char c)/valueOf(int i)/valueOf(double d))

public String valueOf(char[] data)::将字符数组转换成一个字符串并返回

char[] chs = {'1','2','3'};
String s = String.valueOf(chs);
System.out.println(s);
  • 1.
  • 2.
  • 3.
123
  • 1.

8 将字符串转换为字节数组(getBytes())

● public byte[] getBytes():将字符串转换成一个字节数组并返回

String s = "helloworld";
byte[] bytes = s.getBytes();
for(int i=0;i<bytes.length;i++) { 
    System.out.print(bytes[i]+",");
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
104,101,108,108,111,119,111,114,108,100,
  • 1.

9 拆分字符串为字符串数组(split(String regex))

● public String[] split(String regex):将字符串按照给定regex(正则表达式)拆分为字符串数组,并返回

String s = "aa,bb,cc"; 
String[] strArray = s.split(",");
for(int i=0;i<strArray.length;i++) { 
    System.out.println(strArray[i]);
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
aa 
bb 
cc
  • 1.
  • 2.
  • 3.