繁体   English   中英

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

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

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

这是我的功能代码

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

该函数应返回字符的位置,如果字符不存在,则返回应为:NOT_IN_STRING

即使在字符串中找到目标字符,也不会中断循环。 因此,字符串的长度将作为目标字符的索引返回。

函数返回类型为size_t而不是int的对象也更好。

并且函数声明应该看起来像

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

那就是指针应该有限定符const因为字符串在函数内部没有改变。

考虑到C标准包括几乎类似的函数strchr ,其声明如下:

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

这是一个演示程序,显示了如何实现该功能。

#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] ) );
    }
}

程序输出为

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

所示函数从搜索中排除终止零。 如果要在搜索中包含终止零,则只需按照以下方式更改函数的return语句即可

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

考虑使用char *strchr(const char *string, int c); 来自标准库。

无论如何,该功能应通过以下方式完成:

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

不要使用所有这些索引。 太难读了。

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

在这里,您还有另一个选择:

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

这里是比较https://godbolt.org/z/uCBRm2

此代码中的几个问题。 首先,如果在字符串中找到字符,则标记为flag++但是如果字符在字符串中多次出现,会发生什么呢? 该标志将为2,3等。这样,您将只有该字符在字符串中的最后一个索引。 为了解决这个问题,需要添加for循环str[i] && !flag 另外,您还要检查char是否等于int而不进行任何强制转换( str[i] == c ),可以通过函数atoi()或常规的简单强制转换来更改它。 祝好运! 詹姆士

暂无
暂无

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

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