java - java中循环迭代时如何计算特定字符串是否匹配?

标签 java for-loop iterator bluej

这是我过去未能及时完成的​​作业。我是一名新程序员,正在努力解决字符搜索程序的这种方法。我一直困惑于 if 语句使用哪个 boolean 逻辑,以及如何使用预定义的字符变量在短语中查找匹配项。示例测试是:character = "x",phrase = "Xerox"。而 X 和 x 是不同的。预期输出应为 count = 1。 编辑:这个问题应该在不使用数组或列表的情况下得到回答。

 /**
 * Counts and returns the number of times the letter for this class 
 * occurs in the phrase. The class is case sensitive. 
 */
public int letterCount(String phrase)
{  
    Scanner jf = new Scanner(phrase);
    count = 0;
    for (int i = phrase.length(); i > 0; i--)
    { 
        jf.findInLine(character);         
        if(jf.hasNext())
        {
            count++;
            jf.next(); 


        }             
    }
    return count;
}

最佳答案

给你:

/**
 * Counts and returns the number of times the letter for this class 
 * occurs in the phrase. The class is case sensitive. 
 */
public int letterCount(String phrase)
{
    int count = 0;
    // for every character in phrase ...
    for (int i = 0; i < phrase.length(); i++)
    { 
        // ... if it is the right one ...
        if(phrase.charAt(i) == character)
        {
            // ... increment the counter
            count++;
        }
    }
    return count;
}

您不需要任何扫描仪,并且代码相当简单、可读且易于理解。

关于java - java中循环迭代时如何计算特定字符串是否匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29399837/

相关文章:

c++ - 一行 std::vector ctor 映射另一个 vector ?

java - 在Java中拉伸(stretch)图像

java - v7 getSupportActionBar() 抛出 NullPointerException

Java Swing 调整 BorderLayout.CENTER 大小

javascript - for 循环内的条件未通过。为什么?

ios - 在 Swift 中将文本添加到 TextView

java - 多个程序访问同一个 mySQL 数据库

JavaScript 循环语法

c++ - 使用迭代器从 vector 中查找子字符串

java - 具有类型混淆的自定义 Java 迭代器