首页 > 编程语言 > 详细

JAVA——String类indexOf()和substring()用法详解

时间:2020-06-23 11:44:39      阅读:65      评论:0      收藏:0      [点我收藏+]

indexOf()的四种用法

indexOf(int ch)
返回指定字符在此字符串中第一次出现处的索引,未找到返回-1。
例如

String str1="01234543210";
char ch=‘2‘;
System.out.println( str1.indexOf(ch) );

输出结果:2
indexOf(int ch, int fromIndex)
从指定的索引开始搜索,返回指定字符在此字符串中第一次出现处的索引,未找到返回-1。
例如

String str1="01234543210";
char ch=‘2‘;
System.out.println( str1.indexOf(ch,4));

输出结果:8
indexOf(String str)
返回指定字符串在此字符串中第一次出现处的索引,未找到返回-1。
例如

String str1="012345012345";
String str2="123";
System.out.println( str1.indexOf(str2));

输出结果:1
indexOf(String str, int fromIndex)
从指定的索引开始搜索,返回指定字符串在此字符串中第一次出现处的索引,未找到返回-1。
例如

String str1="012345012345";
String str2="123";
System.out.println( str1.indexOf(str2,2));

输出结果:7

substring()的两种用法

substring(int beginIndex)
返回该字符串的子字符串,子字符串从指定索引处的字符开始,直到该字符串的末尾结束。
例如

String str1="happyday";
System.out.println(str1.substring(2));

输出结果:"ppyday"
substring(int beginIndex, int endIndex)
返回该字符串的子字符串,子字符串从指定的索引beginIndex处开始,直到索引endIndex - 1处结束。因此子字符串的长度是endIndex-beginIndex。
例如

String str1="happyday";
System.out.println(str1.substring(2,6));

输出结果:"ppyd"

JAVA——String类indexOf()和substring()用法详解

原文:https://www.cnblogs.com/weiyining/p/13181016.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!