java字符串基本操作

一、获取字符串的长度:

方法:public int length()
注:成员方法带括号不同于获取数组长度。
Demo:

String str = "123456789";
System.out.println(str.length());
10

二、获取指定位置的字符:

方法:public char charAt(int index)
Demo:

String str = "123456789";
System.out.println(str.charAt(3));
4

三、获取子字符串索引位置:

方法:
(1)public int indexOf(String str)获取第一次出现的索引。
(2)public int indexOf(String str,int fromlndex)从指定位置往后查。
(3)public int lastIndexOf(String str)获取最后一次出现的索引。
(4)public int lastIndexOf(String str,int fromlndex)从指定位置往前查。

Demo:
(1)

String str = "We are the world";
int index = str.indexOf("e");
System.out.println(index);
1

(2)

String str = "We are the world";
int index = str.indexOf("e", 3);
System.out.println(index);
5

(3)

String str = "We are the world";
int index = str.lastIndexOf("e");
System.out.println(index);
9

(4)

String str = "We are the world";
int index = str.lastIndexOf("e",8);
System.out.println(index);
5
原创文章 14 获赞 12 访问量 1203

猜你喜欢

转载自blog.csdn.net/weixin_45713984/article/details/105757677