index of string in multiple positions

戏子无情 提交于 2020-01-05 20:29:53

问题


I want to be able to get the multiple index values of a certain string, for example;

System.out.print("Enter an Integer:");

Scanner input = new Scanner(System.in);
String primeNumber = input.nextLine();

System.out.printf("\n%s",primeNumber.indexOf('2'));

when an input of 2589729872 is entered, I get a result of 0.

I want to obtain 0,5 and 9. How would I go about this?


回答1:


Scanner input = new Scanner(System.in);

String primeNumber = input.nextLine();

int index = primeNumber.indexOf('2');

while(index >=0) {

System.out.println(index);
index = primeNumber.indexOf('2',index+1);

}




回答2:


If you just want to print them, this should be sufficient, otherwise you could also store them in an array and print them later.

System.out.print("Enter an Integer:");

Scanner input = new Scanner(System.in);
String primeNumber = input.nextLine();
int index = -1;

while ((index = primeNumber.indexOf('2', index + 1)) != -1) {
    System.out.printf("%d,", index);
}
System.out.printf("\n");



回答3:


With Java 8 you can do this:

IntStream.range(0, primeNumber.length())
    .filter(j -> primeNumber.charAt(j) == '2')
    .forEach(System.out::println);



回答4:


You could try something like this:

int length = primeNumber.length();

for(int i = 0 ; i < length; i++){
    if(primeNumber.charAt(i)== '2'){
    System.out.println(i);
    }

}


来源:https://stackoverflow.com/questions/29595501/index-of-string-in-multiple-positions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!