字符串

字符串与字符

//字符要用单引号,字符串用双引号
char a={'h','e','l','l','o'}
String a= new String(a)
//上面两行等价于
String a = new String("hello")

字符串的相关方法

1. 获取字符串长度

str.length()

实例:

//用整型变量a获取字符串s的长度

String s=new String("HelloWorld");

int a=s.length;

 

2. 字符串的查找

2.1 indexOf()

这个方法用于返回参数字符串在指定字符串首次出现的位置 

//使用a获取字母o最后一次在字符串s中出现的索引位置
//最后一次出现在6,也就是a=6
String s = new String("HelloWorld");
int a=s.indexOf("o");

 

2.2 lastIndexOf()

与上一个方法正相反,这个方法返回参数字符串在指定字符串中最后一次出现的位置

实例:

//使用a获取字母o第一次在字符串s中出现的位置
//第一次出现在4,也就是a=4,因为是从0开始数
String s = new String("HelloWorld");
int a=s.indexOf("o");

3. 获取指定索引位置的字符

str.charAt(int index)

返回参数所定位指定字符串中的字符

实例:

//字符变量a获取字符串s索引位为8的字符,a为'r'.
String s = new String("Hello world!");
char a = s.charAt(8);

 

4.获取子字符串

4.1 str.substring(int index)

获取从指定的索引位置截取到最后的字符串

实例:

//用字符串a获取字符串s索引3及以后的子字符串,a="o world!"
String s= new String("Hello world!");
String a=s.substring(5);

4.2 str.substring(int beginIndex,int endIndex)

获取从第一个参数到第二个参数的子字符串

实例:

//a="lo "
String s = new String("Hello world!");
String a = s.substring(3,5);

5.去除空格

str.trim()

去除字符串中的空格

//a="Helloworld!"
String s = new String("  H ello wo rld ! ");
String a = s.trim();

6. 字符串替换

str.replace(char newChar,char oldChar);

 

未完待续。。。

 

posted @ 2020-07-31 00:42  helex  阅读(141)  评论(0编辑  收藏  举报