繁体   English   中英

使用Java中的indexOf查找字符串中的空格

[英]Finding Spaces In A String Using indexOf in Java

所以我正在尝试编写一个方法,它将返回另一个字符串中String的出现次数。 在这种情况下,它会找到String中的空格数。 就像indexOf()没有识别空格一样。

这是我的方法:

public int getNumberCardsDealt()
{
    int count = 0;
    int len2 = dealtCards.length();

    int foundIndex = " ".indexOf(dealtCards);

    if (foundIndex != -1)
    {
        count++;
        foundIndex = " ".indexOf(dealtCards, foundIndex + len2);
    }

    return count;
}

这是我的申请:

public class TestDeck
{
public static void main(String [] args)
{
    Deck deck1 = new Deck();

    int cards = 52;
    for(int i = 0; i <= cards; i++)
    {
        Card card1 = deck1.deal();
        Card card2 = deck1.deal();
    }

    System.out.println(deck1.cardsDealtList()); 
    System.out.println(deck1.getNumberCardsDealt());
}
}

请注意,我已经有了Card类, deal方法也有效。

检查indexOf方法的文档。 你错了。

您应该更改调用

" ".indexOf(dealtCards);

dealtCards.indexOf(" ");

也就是说,在相关字符串上调用该方法并向其传递您要查找的字符,而不是相反。


此外,无论如何,您的方法无法正确计算它,您应该将其更改为:

public int getNumberCardsDealt() {
    int count = 0;
    int foundIndex = -1; // prevent missing the first space if the string starts by a space, as fixed below (in comments) by Andy Turner

    while ((foundIndex = dealtCards.indexOf(" ", foundIndex + 1)) != -1) {
        count++;
    }

    return count;
}

@ A.DiMatteo的答案为您提供了indexOf当前不起作用的原因。

在内部, String.indexOf基本上只是迭代字符。 如果你总是只是寻找一个角色,你可以自己做这个迭代来做计数:

int count = 0;
for (int i = 0; i < dealtCards.length(); ++i) {
  if (dealtCards.charAt(i) == ' ') {
    ++count;
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM