循环遍历字符串,直到达到特定字符

时间:2014-05-11 07:32:17

标签: string for-loop while-loop substring

我试图在字符串中的字母不等于特定字符(例如 a )时将整数递增1,

例如, dfla 的字符串将计为3.因为循环将在'a'处中断。

我怎么能这样做?

private int countToFirstCharacter(String name, String character) {

    int count = 0;

    for (int i = 0; i < materialName.length(); i++) {

        //Increment count if it isn't equal to a, then break loop.
        //Stuck here.

    }

    return count;

}

2 个答案:

答案 0 :(得分:0)

无需循环:

string s = "dfla";
int x = s.IndexOf("a"); // It will show you 3

另一种解决方案可以是:

private static int countToFirstCharacter(String name, char character)
{

    int count = 0;

    for (int i = 0; i < name.Length; i++)
    {
        if (name[i].Equals(character))
            break;
        else
            count++;
    }

    return count;

}

答案 1 :(得分:-1)