Ras*_*var 8 java string character indices
如何在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));
}
}
Run Code Online (Sandbox Code Playgroud)
你几乎是对的。问题是你的最后一行。您应该打印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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
56346 次 |
| 最近记录: |