A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© liyin 中级黑马   /  2014-6-3 16:57  /  1308 人查看  /  9 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. str.indexOf(substr)
复制代码

今天看到的一个字符串查找语法;
问题就是我想查找students中“s”的位置时只反馈第一个“s”的位置;
有什么其他方法可以直接反馈两个“s”的位置吗?

9 个回复

倒序浏览
可以通过toCharArray()先把字符串转成字符数组,然后通过遍历找出字符位置
例:
                String s = "students";
                char[] ch = s.toCharArray();
                for(int i = 0; i < ch.length; i++)
                {
                        if('s' == ch[i])
                                System.out.println("位置是:" + i);
                }
回复 使用道具 举报
提菩--空 发表于 2014-6-3 18:01
可以通过toCharArray()先把字符串转成字符数组,然后通过遍历找出字符位置
例:
                String s  ...

楼上正解
回复 使用道具 举报
你用for循环变量字符串就行
  1. public class S{
  2.         public static void main(String[] args) {
  3.                 String str = "super start";
  4.                 for (int i = 0; i < str.length(); i++) {
  5.                         char c=str.charAt(i);
  6.                         if(c=='s'){
  7.                                 System.out.println(i);
  8.                         }
  9.                 }
  10.                
  11.                
  12.         }
  13. }
复制代码
回复 使用道具 举报
可以通过indexOf(String str, int fromIndex),先从0号位开始查找,查到返回并打印,
然后fromIndex++,跳到下一个开始读取位置,一直循环到indexOf返回-1

  1. public class Test {
  2.     public static void main(String[] args) {
  3.         // TODO Auto-generated method stub
  4.         int index = 0;
  5.         String str = "supser sutring";
  6.         while((index = str.indexOf("s", index))!=-1)
  7.         {
  8.             System.out.println(index);
  9.             index++;
  10.         }
  11.             
  12.     }
  13. }
复制代码
回复 使用道具 举报
楼上已经有了答案了  主要是要遍历  找到相同的字符  就返回角标
回复 使用道具 举报
提菩--空 发表于 2014-6-3 18:01
可以通过toCharArray()先把字符串转成字符数组,然后通过遍历找出字符位置
例:
                String s  ...

谢谢了:handshake
回复 使用道具 举报
关于查询字符串中某个字符或者字符串位置的方式很多 ,楼上的都可以实现,学习了
回复 使用道具 举报
More 发表于 2014-6-3 18:21
你用for循环变量字符串就行

谢了:lol:lol
回复 使用道具 举报
我来学习了!!!!!!!!!!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马