在字符串中查找字符的位置

9

如何在一个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));
    }
}

如果您期望代码,请编辑您的问题并添加一个标签,告诉我们您正在使用的语言/环境。此外,您自己是否尝试过?如果是,请也添加进来。 - Damien_The_Unbeliever
我编辑了我的问题,这个格式是这样的吗? - Rastin Radvar
6个回答

5

您几乎是正确的。问题出在您的最后一行。您应该打印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);
    }
}

@RastinRadvar 当一个答案对你有用时,你应该接受它。 - Étienne Miret
谢谢,伙计,搞定了。我是新来的,还不知道怎么操作。我很快就会弄清楚一切的,再次感谢你的帮助 :) - Rastin Radvar

0
这里是一个函数,用于在字符串中找到特定字符的所有位置。
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

0
    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

谢谢,这也可以工作,但我不想使用数组。我找到了我的答案,但非常感谢你的帮助 :) - Rastin Radvar

0

在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);
        }   
    }

0

从第一个字符开始迭代遍历所有字符,直到到达结尾。在每个步骤中测试该字符是否为“o”。如果是,则打印位置。


0
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.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接