-1

I would like to have this code be able to locate more than one X and output it as Location1, location2,.......

i.e input: xuyx i would have it output 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);
    }






    }
}
Assaf
  • 1,352
  • 10
  • 19
  • possible duplicate of [Java - Indexes of all occurrences of character in a string](http://stackoverflow.com/questions/5034442/java-indexes-of-all-occurrences-of-character-in-a-string) – Ravi Yenugu Sep 04 '14 at 20:22

2 Answers2

2

String has the method indexOf(String str, int fromIndex) http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

So just increment the starting index to where you found the last one.

String xStr = "xuyx";

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

or better yet...

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;
}
damian
  • 1,419
  • 1
  • 22
  • 41
0

You could do it like this. Iterate through the characters and print out the indexes where you hit an 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();
}

Bear in mind you'd have to fix the case if you want to detect capital X as well. Or, as kingdamian42 says, you could use indexOf(txt, fromindex)

khelwood
  • 55,782
  • 14
  • 81
  • 108