如果字符串包含至少一个c,那么我如何打印第一个" c"的位置?

时间:2018-02-02 19:05:26

标签: java

我正在尝试解决这个问题集:如果字符串包含至少一个c,那么我如何打印第一个" c"的位置?信?

我在运行此代码时只获得位置0,即使c位于另一个位置。

import javax.swing.JOptionPane;

public class innlev3 {

    public static void main(String[] args) {

        String i;

        i = (JOptionPane.showInputDialog("Write a word: "));

        int position = getPosition(i);

        if (i.contains("c")) {
            JOptionPane.showMessageDialog(null, "The position of the letter c is: " + position);
        } else {
            JOptionPane.showMessageDialog(null, "Strengen inneholder ikke noen bokstaver med c.");
        }
    }

    private static int getPosition(String i) {
        return 0;
    }
}

5 个答案:

答案 0 :(得分:4)

使用String#indexOf打印位置:

if (i.contains("c")) {
    JOptionPane.showMessageDialog(null, "The position of the letter c is: " + i.indexOf("c"));
} else {
    JOptionPane.showMessageDialog(null, "Strengen inneholder ikke noen bokstaver med c.");
}

答案 1 :(得分:2)

int position = i.indexOf('c');

答案 2 :(得分:2)

你可以借助String类

中的indexOf(int ch)方法来完成它

https://docs.oracle.com/javase/9/docs/api/java/lang/String.html#indexOf-int-

  

返回指定字符第一次出现的字符串中的索引。

答案 3 :(得分:1)

使用String::indexOf

private static int getPosition(String i, char search) {
    return i.indexOf(search);
}

然后使用它:

int position = getPosition(i, 'c');

答案 4 :(得分:1)

将您的getPosition方法替换为以下方法:

private static int getPositionOfC(String i) {
   return i.indexOf('c');
}