请教一个问题我想要得到指定字符第N次出现时的其位置索引 该如何实现?比如 str="This is a string string string" 如何得到从左起空格字符第三次出现的位置索引9。 IndexOf函数只能实现第一次出现的位置索引

解决方案 »

  1.   

    indexOf(String str) 
              
     int indexOf(String str, int fromIndex) 从指定的索引处开始,返回第一次出现的指定子字符串在此字符串中的索引。 
    这2个结合起来用
     
      

  2.   

    int n = ?;//n表示第几次出现
    String str="This is a string string string"  
    char c = "?"//c表示要计算第几次出现的字符
    int count = 0;
    public int returnMethod(int n,String str)
    {
       int index;
       for(int i =0;i<str.length();)
       {
         index = str.indexof(c,i);
         if(count == n)
         {
             return index;     
         }
       }
       return -1;
    }
      

  3.   

    public int func(String str,char c,int n)//字符串,要查找的字符,指定的次数
    {
        if(n<=0)return -1; 
           
        for(int i=0;i<str.length;++i)
        {
             if(c==str.charAt(i))
             {
                --n;
                if(0==n)return i;
             }
        }    return -1;
    }
        
      

  4.   

    import java.io.*;
    calss select{
    public void main(String as[])
    throws Exception{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    String str=br.readLine();
    int number=str.indexOf(" "),i;
    for(i=0;i<n-1;i++){
    number=str.indexOf(" ",number+1);
    }
    System.out.println(“第”+i+“字符的索引号:”+number);
    }
    }
      

  5.   

    上面胡有错,这要些的,大家看看有什么错误啊,指点一下了
    mport java.io.*; 
    calss select{ 
    public void main(String as[]) 
    throws Exception{ 
    System.out.print("请输入要查找的个数:");
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 
    String str1=br.readLine(); 
    int n=Integer.parseInt(str1);
    String str="This is a string string string";
    int number=str.indexOf(" "),i; 
    for(i=0;i <n-1;i++){ 
    number=str.indexOf(" ",number+1); 

    System.out.println(“第”+i+“字符的索引号:”+number); 

    }
      

  6.   


    public class Ex {
    public static int index(String s,char c,int i){
    int count = 0;
    for(int j=0;j<s.length();j++){
    if(s.charAt(j)==c&&++count==i)
    return j;
    }
    return -1;
    }
    public static void main(String[] args){
    String str = "This is a string string string";
    char ch = ' ';
    System.out.println(index(str,ch,3));
    }
    }