简体   繁体   English

查找字符串中字符的第一个索引

[英]Find the first index of a character in a string

I am supposed to loop through the character of arrays that is passed in and look for the first occurrence of char, then return the index of the first occurrence. 我应该遍历传入的数组的字符并查找char的第一次出现,然后返回第一次出现的索引。 if char is not found then I return -1. 如果找不到char,则返回-1。 This seems to work for all characters except the character at 0, which it does not find for some reason. 这似乎适用于除0字符以外的所有字符,由于某种原因找不到0。

int find_ch_index(char string[], char ch) {
    int i = 0;
    while (string[i++]) {
            if (string[i] == ch) {
                    return i;
            }
    }
    return -1;
}

You should increment i at the end of the while loop: 您应该在while循环结束时增加i:

int find_ch_index(char string[], char ch) {
    int i = 0;
    while (string[i]) {
        if (string[i] == ch) {
            return i;
        }
        i++
    }
    return -1;
}

You won't find the first char ever, because: while (string[i++]) 您将找不到有史以来的第一个字符,因为:while(string [i ++])

Increments i from '0' to '1', so the statement at 'if' never compares the first char. 将i从“ 0”递增到“ 1”,因此“ if”处的语句从不比较第一个字符。

Quit this increment and do it at the end of the loop. 退出此增量并在循环结束时执行。

我正在while循环中从0增加到1。

In the while condition 在一段时间条件下

while (string[i++]) {

you increased index i. 您增加了索引i。 Thus in the next statement 因此,在下一条语句中

        if (string[i] == ch) {

you are using the increased index. 您正在使用增加的索引。

The function can be written the following way 该函数可以通过以下方式编写

int find_ch_index( const char string[], char ch ) 
{
    int i = 0;

    while ( string[i] && string[i] != ch ) i++;

    return string[i] == ch ? -1 : i;
}

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

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