超过一个索引

时间:2014-09-04 19:52:03

标签: java

我希望此代码能够找到多个X并将其输出为Location1,location2,.......

即输入:xuyx 我会输出0,3

import java.util.Scanner;

public class findinline {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String str;

    str = input.nextLine();
    int pos = str.indexOf("x");

    if (pos < 0){
    System.out.println("No X Detected");
    }
    else{
        System.out.println(pos);
    }






    }
}

2 个答案:

答案 0 :(得分:2)

String的方法为indexOf(String str, int fromIndex) http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

所以只需将起始索引增加到找到最后一个索引的位置。

String xStr = "xuyx";

int index = xStr.indexOf("x", 0);
while(index >= 0)
{
  System.out.println(index);
  index = xStr.indexOf("x", index + 1);
}

或更好......

public List<Integer> getIndexesOfStr(String fullStr, String strToFind){
  ArrayList<Integer> listOfIndexes = new ArrayList<>();

  int index = fullStr.indexOf(strToFind, 0);
  while(index >= 0)
  {
    listOfIndexes.add(index);
    index = fullStr.indexOf(strToFind, index + strToFind.length());
  }
  return listOfIndexes;
}

答案 1 :(得分:0)

你可以这样做。遍历字符并打印出符合x的索引。

boolean any = false;
for (int pos = 0; pos < str.length(); ++pos) {
    if (str.charAt(pos)=='x') {
        if (any) {
            System.out.print(',');
        }
        any = true;
        System.out.print(pos);
    }
}
if (!any) {
    System.out.println("No x found");
} else {
    System.out.println();
}

请记住,如果您想要检测大写字母X,则必须修复此案例。 或者,正如kingdamian42所说,你可以使用indexOf(txt, fromindex)