【问题标题】:How to find number the number of a specific character in a word?如何查找单词中特定字符的编号?
【发布时间】:2013-07-04 09:48:55
【问题描述】:

我正在尝试制作一个程序,只要找到一个字符(用于检查'a'),它就会打印它并继续检查下一个字符。一直这样做,直到 word.length 结束。 这是我到目前为止所做的,但不起作用,

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter a word: ");
    String word = in.next();
    String a = "a";
    int i;
    char found = 0;
    char F;

    for (i = 0; i < word.length(); i++)
    {
        F = word.charAt(i);

        if (F == found)
        {
            System.out.println(i);
        }

    }


}

【问题讨论】:

  • 怎么不行?你得到什么输出?
  • 您正在比较 found 而不是 a...
  • 不要自己调试
  • @RohitJain 我没有得到任何输出。
  • @Aquillo 但我无法将 a 与 F 进行比较,因为 F 是一个字符。

标签: java string for-loop char string-length


【解决方案1】:

试试

       Scanner in = new Scanner(System.in);
        System.out.print("Enter a word: ");
        String word = in.next();
        Pattern p=Pattern.compile("a");
        Matcher matcher=p.matcher(word);
        boolean b=false;
        while(b=matcher.find())
        {
            System.out.println(matcher.start()+"");
        }

编辑:

Pattern.compile("a");

Compiles the given regular expression into a pattern

p.matcher(word);

Creates a matcher that will match the given input against this pattern. 

如果您想搜索像aba 这样的源字符串,那么对于所有出现的表达式a,它都会这样做

source:aba
index:012

我们可以看到表达式 a 出现了两次:一次从位置 0 开始,第二次从位置 2 开始。所以输出为 0 2

【讨论】:

  • 感谢您的帖子。它没有用,但对我来说看起来很复杂。我还没有学习模式和匹配器。
  • 你不认为为这个问题引入正则表达式,特别是当 OP 正在学习编程基础时,是一种过度杀戮吗??
  • @AlexJj 没关系。我编辑了答案来解释你。因此您也可以使用正则表达式实现相同的功能。由于您对if 条件的问题,所以请更改if(F=='a') 条件。
【解决方案2】:

试试这个

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter a word: ");
    String word = in.next();        
    char F;

    for (int i = 0; i < word.length(); i++) {
        F = word.charAt(i);
        if (F == 'a') {
            System.out.println(i);
        }
    }
}

【讨论】:

    【解决方案3】:

    使用这个简单

     string.indexOf("a");
    

    【讨论】:

    • 感谢您的帖子,但我应该在哪里替换它?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    相关资源
    最近更新 更多