java中j字符串截取子串的使用(subString();indexOf();)

substring(firstIndex,endIndex){//返回从首到尾的字符串};

substring(firstIndex){//返回firstIndex到结尾的字符串};

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_27093465/article/details/51832189

  Java中字符串中子串的查找共有四种方法(indexof())
indexOf 方法返回一个整数值,指出 String 对象内子字符串的开始位置。如果没有找到子字符串,则返回-1。
如果 startindex 是负数,则 startindex 被当作零。如果它比最大的字符位置索引还大,则它被当作最大的可能索引。

Java中字符串中子串的查找共有四种方法,如下:
1、int indexOf(String str) :返回第一次出现的指定子字符串在此字符串中的索引。 
2、int indexOf(String str, int startIndex):从指定的索引处开始,返回第一次出现的指定子字符串在此字符串中的索引。 
3、int lastIndexOf(String str) :返回在此字符串中最右边出现的指定子字符串的索引。 
4、int lastIndexOf(String str, int startIndex) :从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的指定子字符串的索引。


 
 
  1. public class Test {
  2. public static void main(String[] args) {
  3. String s = "xXccxxxXX";
  4. // 从头开始查找是否存在指定的字符 //结果如下
  5. System. out.println(s.indexOf( "c")); //2
  6. // 从第四个字符位置开始往后继续查找,包含当前位置
  7. System. out.println(s.indexOf( "c", 3)); //3
  8. //若指定字符串中没有该字符则系统返回-1
  9. System. out.println(s.indexOf( "y")); //-1
  10. System. out.println(s.lastIndexOf( "x")); //6
  11. }
  12. }

虽然简单,我就做个笔记。


 
 
  1. private static void testIndexOf() {
  2. String string = "aaa456ac";
  3. //查找指定字符是在字符串中的下标。在则返回所在字符串下标;不在则返回-1.
  4. System. out.println( string.indexOf( "b")); //indexOf(String str);返回结果:-1,"b"不存在
  5. // 从第四个字符位置开始往后继续查找,包含当前位置
  6. System. out.println( string.indexOf( "a", 3)); //indexOf(String str, int fromIndex);返回结果:6
  7. //(与之前的差别:上面的参数是 String 类型,下面的参数是 int 类型)参考数据:a-97,b-98,c-99
  8. // 从头开始查找是否存在指定的字符
  9. System. out.println( string.indexOf( 99)); //indexOf(int ch);返回结果:7
  10. System. out.println( string.indexOf( 'c')); //indexOf(int ch);返回结果:7
  11. //从fromIndex查找ch,这个是字符型变量,不是字符串。字符a对应的数字就是97。
  12. System. out.println( string.indexOf( 97, 3)); //indexOf(int ch, int fromIndex);返回结果:6
  13. System. out.println( string.indexOf( 'a', 3)); //indexOf(int ch, int fromIndex);返回结果:6
  14. //这个就是灵活运用String类提供的方法,拆分提供的字符串。
  15. //String s = "D:\\Android\\sdk\\add-ons";
  16. //System.out.println(s);
  17. //while (s.lastIndexOf("\\") > 0) {
  18. // s = s.substring(0, s.lastIndexOf("\\"));
  19. // System.out.println(s);
  20. //}
  21. }

上面代码的运行结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值