如何在
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);
}
}
从第一个字符开始,迭代所有字符,直到到达末尾。在每个步骤中测试该字符是否是“o”。如果是,则打印位置。
这里是 Java:
String s = "you are awesome honey";
char[] array = s.toCharArray();
for(int i = 0; i < array.length; i++){
if(array[i] == 'o'){
System.out.println(i);
}
}
static ArrayList<String> getCharPosition(String str, char mychar) {
ArrayList<String> positions = new ArrayList<String>();
if (str.length() == 0)
return null;
for (int i = 0; i < str.length(); i ++) {
if (str.charAt(i) == mychar) {
positions.add(String.valueOf(i));
}
}
return positions;
}
String string = ("You are awesome honey");
ArrayList<String> result = getCharPosition(string, 'o');
for (int i = 0; i < result.size(); i ++) {
System.out.println("char position is: " + result.get(i));
}
输出:
char position is: 1
char position is: 12
char position is: 17
这是查找字符串中特定字符的所有位置的函数
public ArrayList<Integer> findPositions(String string, char character) {
ArrayList<Integer> positions = new ArrayList<>();
for (int i = 0; i < string.length(); i++){
if (string.charAt(i) == character) {
positions.add(i);
}
}
return positions;
}
并使用它
ArrayList<Integer> result = findPositions("You are awesome honey",'o');
// result will contains 1,12,17
public class Test {
//Please remember that the first array position will always start from 0
public static void main(String[] args){
String name = ("Renuncia Boric!!!");
for (int i = 0 ; i<name.length() ; i++)
if (name.charAt(i) == 'i')
System.out.println("The letter selected is present at the position: "+i+".");
}
}
输出:
The letter selected is present at the position: 6.
The letter selected is present at the position: 12.