如何在a中找到字符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);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句