Java学习笔记95——String类的获取功能
String类的获取功能
1、获取字符串的长度
int length()
2、返回char字符指定位置索引的值,索引从0开始到length()-1
char charAt(int index)
3、返回指定字符第一次出现的字符串内的索引如果此字符串中没有此类字符,则返回-1
int indexOf(int ch)
4、返回的是字符串第一个字符在大字符串中的索引值,如果k的值不存在,则返回-1
int indexOf(String str)
5、返回指定字符第一次出现在字符串中的索引,以指定的索引开始搜索1、规定了想要搜索的字符 2、搜索的起点
int indexOf(int ch,int fromIndex)
6、返回指定String字符第一次出现在字符串中的索引,以指定的索引开始搜索
int indexOf(String str,int fromIndex)
String substring(int start)
8、返回的是一个字符串,该字符串是此字符串的子字符串,字串开始于start位置,并截取到end-1的位置,左闭右开 [ , ) 含头不含尾
String substring(int start,int end)
public class StringDemo7 {
public static void main(String[] args) {
String s = "helloworld";
//int length() 获取字符串的长度
System.out.println(s.length());
System.out.println("*************************");
//char charAt(int index) 返回char字符指定位置索引的值
//索引从0开始到length()-1
System.out.println(s.charAt(7));
System.out.println(s.charAt(0));
//StringIndexOutOfBoundsException
// System.out.println(s.charAt(100));
System.out.println("*************************");
//int indexOf(int ch)
//返回指定字符第一次出现的字符串内的索引
//如果此字符串中没有此类字符,则返回-1 。
System.out.println(s.indexOf('l'));
System.out.println(s.indexOf(97));
System.out.println("*************************");
//int indexOf(String str)
//helloworld
//返回的是字符串第一个字符在大字符串中的索引值
//如果k的值不存在,则返回-1
System.out.println(s.indexOf("owo"));
System.out.println(s.indexOf("qwer"));
System.out.println("*************************");
//int indexOf(int ch,int fromIndex)
//返回指定字符第一次出现在字符串中的索引,以指定的索引开始搜索
//1、规定了想要搜索的字符 2、搜索的起点
System.out.println(s.indexOf('l',4));//8
System.out.println(s.indexOf('p',4)); //-1
System.out.println(s.indexOf('l',40));//-1
System.out.println(s.indexOf('p',40));//-1
System.out.println("*************************");
//int indexOf(String str,int fromIndex)
System.out.println("*************************");
//String substring(int start)
//返回的是一个字符串,该字符串是此字符串的子字符串
//子字符串从指定的索引处开始,并扩展到字符串的末尾
//包含开始索引位置的值
//helloworld
System.out.println(s.substring(3)); //loworld
//.StringIndexOutOfBoundsException
// System.out.println(s.substring(20));
System.out.println("*************************");
//String substring(int start,int end)
//返回的是一个字符串,该字符串是此字符串的子字符串
//字串开始于start位置,并截取到end-1的位置
//左闭右开 [,) 含头不含尾
System.out.println(s.substring(5,10));//world(在字符串中从第六个字符开始到第十个字符结束)
//StringIndexOutOfBoundsException
// System.out.println(s.substring(1,20));

浙公网安备 33010602011771号