简体   繁体   English

查找字符串C中字符的第一个位置

[英]Find the first position of a character in string C

Find the first position of a character c in string 查找字符串中字符c的第一个位置

Here is my code of the function 这是我的功能代码

int char_index(int c, char *string) {
    int flag = 0;
    int i = 0;
    int index = 0;

    for(i = 0; string[i] != '\0'; i++){
        if (string[i] == c){
            flag++;
        }
        if (flag == 0){
            index = NOT_IN_STRING;
        } 
        else {
            index = i+1;
        }
    }
    return index;
}

The function is expected to return the position of the character, if the character doesn't exist, the return should be : NOT_IN_STRING 该函数应返回字符的位置,如果字符不存在,则返回应为:NOT_IN_STRING

You do not interrupt the loop even when the target character is found in the string. 即使在字符串中找到目标字符,也不会中断循环。 So the length of the string will be returned as an index of the target character. 因此,字符串的长度将作为目标字符的索引返回。

Also it is better when the function returns an object of type size_t instead of int . 函数返回类型为size_t而不是int的对象也更好。

And the function declaration should look like 并且函数声明应该看起来像

size_t char_index( const char *s, char c );

that is the pointer shall have the qualifier const because the string is not changed inside the function. 那就是指针应该有限定符const因为字符串在函数内部没有改变。

Take into account that the C standard includes almost a similar function strchr that is declared like 考虑到C标准包括几乎类似的函数strchr ,其声明如下:

char * strchr( const char *s, char c );

Here is a demonstrative program that shows how the function can be implemented. 这是一个演示程序,显示了如何实现该功能。

#include <stdio.h>

#define NOT_IN_STRING   ( size_t )-1

size_t char_index( const char *s, char c )
{
    size_t i = 0;

    while ( s[i] != '\0' && s[i] != c ) ++i;

    return s[i] != '\0' ? i : NOT_IN_STRING;
}

int main( void )
{
    const char *s = "Betty";

    for ( size_t i = 0; s[i] != '\0'; i++ )
    {
        printf( "%c: %zu\n", s[i], char_index( s, s[i] ) );
    }
}

The program output is 程序输出为

B: 0
e: 1
t: 2
t: 2
y: 4

The shown function excludes the terminating zero from searching. 所示函数从搜索中排除终止零。 If you want to include the terminating zero in searching then just change the return statement of the function the folloing way 如果要在搜索中包含终止零,则只需按照以下方式更改函数的return语句即可

return s[i] == c ? i : NOT_IN_STRING;

Consider using char *strchr(const char *string, int c); 考虑使用char *strchr(const char *string, int c); from standard library. 来自标准库。

Anyway the function should be done in this way: 无论如何,该功能应通过以下方式完成:

int char_index(char c, char *string) {
    for (int i = 0; string[i] != '\0'; i++)
        if (string[i] == c)
            return i;

    return NOT_IN_STRING;
}

Don't use all those indexes. 不要使用所有这些索引。 It's too difficult to read. 太难读了。

/* Find first occurence of a character in a string. */
#include <stdio.h>

#define NOT_IN_STRING -1

int
char_index(int c, const char *string)
{
        const char *start = string;
        while( *string != c && *string ) {
                string++;
        }
        return ( *string == c) ? string - start : NOT_IN_STRING;
}

int
main(int argc, char **argv)
{
        const char *needle = argc > 1 ? argv[1] : "";
        const char *haystack = argc > 2 ? argv[2] : "abcdefgh";

        printf("Target string: %s\n", haystack);
        while(*needle) {
                printf("\t%c: %d\n", *needle, char_index((int)*needle, haystack));
                needle += 1;
        }
        return 0;
}

Here you have another option: 在这里,您还有另一个选择:

int instring(int c, const char *str)
{
    int result = NOT_IN_STRING;
    const char savedstr = str;

    while(*str)
    {
        if(*str == c)
        {
            result = str - savedstr;
            break;
        }
        str++;
    }
    return result;
}

and here the comparison https://godbolt.org/z/uCBRm2 这里是比较https://godbolt.org/z/uCBRm2

Couple of problems in this code. 此代码中的几个问题。 First the flag, if character is found in the string so flag++ but what happens when the character shows up in the string more than once? 首先,如果在字符串中找到字符,则标记为flag++但是如果字符在字符串中多次出现,会发生什么呢? the flag will be 2,3 etc.. that way you will have only the last index in string that character was. 该标志将为2,3等。这样,您将只有该字符在字符串中的最后一个索引。 To solve that add to for loop str[i] && !flag . 为了解决这个问题,需要添加for循环str[i] && !flag In addition you are checking if a char is equal to int without any casting ( str[i] == c ) change it by function atoi() or regular, simple, casting. 另外,您还要检查char是否等于int而不进行任何强制转换( str[i] == c ),可以通过函数atoi()或常规的简单强制转换来更改它。 Good Luck! 祝好运! James 詹姆士

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

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