简体   繁体   English

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

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

So I am trying to write a Method that will return to me the number of occurrences of a String in Another String. 所以我正在尝试编写一个方法,它将返回另一个字符串中String的出现次数。 In this case it's finding the number of spaces in a String. 在这种情况下,它会找到String中的空格数。 It's as if indexOf() is not recognizing the spaces. 就像indexOf()没有识别空格一样。

Here is my Method: 这是我的方法:

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

Here is my application: 这是我的申请:

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

Note that I already have a Card Class and the deal method works. 请注意,我已经有了Card类, deal方法也有效。

Check the documentation of the indexOf method. 检查indexOf方法的文档。 You are using it wrong. 你错了。

You should change the invocation 您应该更改调用

" ".indexOf(dealtCards);

To

dealtCards.indexOf(" ");

That is, invoking the method on the concerned string and passing to it the character you are looking for, not the other way around. 也就是说,在相关字符串上调用该方法并向其传递您要查找的字符,而不是相反。


Moreover, your method would not calculate it correctly anyway, you should change it to something like: 此外,无论如何,您的方法无法正确计算它,您应该将其更改为:

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's answer gives you the reason why your indexOf doesn't work currently. @ A.DiMatteo的答案为您提供了indexOf当前不起作用的原因。

Internally, String.indexOf is basically just iterating through the characters. 在内部, String.indexOf基本上只是迭代字符。 If you're always just looking for a single character, you can trivially do this iteration yourself to do the counting: 如果你总是只是寻找一个角色,你可以自己做这个迭代来做计数:

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