如何在 String
中找到一个字符并在整个字符串中打印该字符的位置?例如,我想在这个字符串中找到 'o'
的位置:"you are awesome honey"
并得到答案 = 1 12 17
.
我写了这个,但它不起作用:
public class Pos {
public static void main(String args[]){
String string = ("You are awesome honey");
for (int i = 0 ; i<string.length() ; i++)
if (string.charAt(i) == 'o')
System.out.println(string.indexOf(i));
}
}
最佳答案
你几乎是对的。问题是你的最后一行。你应该打印 i
而不是 string.indexOf(i)
:
public class Pos{
public static void main(String args[]){
String string = ("You are awesome honey");
for (int i = 0 ; i<string.length() ; i++)
if (string.charAt(i) == 'o')
System.out.println(i);
}
}
关于java - 查找字符在字符串中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19314228/