Linux下C语言中的字符串比较、查找


=Start=

缘由:

学习、提高需要

正文:

参考解答:
#include <stdio.h>
#include <string.h>
#include <stdbool.h> /* use bool in C */
#include <ctype.h> /* tolower() */
/*
The strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.
返回值 > 0 表示: s1 > s2
返回值 = 0 表示: s1 = s2
返回值 < 0 表示: s1 < s2
int strcmp(const char *s1, const char *s2);
int strncmp(const char *s1, const char *s2, size_t n);
*/
/*
返回值 = 1 表示: str 以 prefix 为前缀
返回值 = 0 表示: str 不以 prefix 为前缀
*/
bool starts_with(const char *str, const char *prefix)
{
    if (!str || !prefix)
        return 0;
   if(strncmp(str, prefix, strlen(prefix)) == 0)
        return 1;
   return 0;
}
/*
返回值 = 1 表示: str 以 suffix 为后缀
返回值 = 0 表示: str 不以 suffix 为后缀
*/
bool ends_with(const char *str, const char *suffix)
{
    if (!str || !suffix)
        return 0;
    size_t lenstr = strlen(str);
    size_t lensuffix = strlen(suffix);
    if (lensuffix > lenstr)
        return 0;
    return strncmp(str + lenstr - lensuffix, suffix, lensuffix) == 0;
}
int ends_withFoo(const char *str) { return ends_with(str, ".foo"); }
/*
返回值 > 0 表示: s1 > s2
返回值 = 0 表示: s1 = s2
返回值 < 0 表示: s1 < s2
*/
int strcicmp(char const *s1, char const *s2)
{
    if (!s1 || !s2)
        return 0;
    for (;; s1++, s2++) {
        int d = tolower(*s1) - tolower(*s2);
        if (d != 0 || !*s1)
            return d;
    }
}
int main(int argc, char const *argv[])
{
    if (argc < 4) {
        printf("Usage:\n\t%s string prefix suffix\n\n", argv[0]);
        return 0;
    }
    if (starts_with(argv[1], argv[2])) {
       printf("'%s' starts_with '%s'\n", argv[1], argv[2]);
    else {
       printf("'%s' not starts_with '%s'\n", argv[1], argv[2]);
    }
    if (ends_with(argv[1], argv[3])) {
       printf("'%s' ends_with '%s'\n", argv[1], argv[3]);
    else {
       printf("'%s' not ends_with '%s'\n", argv[1], argv[3]);
    }
    return 0;
}
参考链接:

Linux下C语言字符串比较
http://man7.org/linux/man-pages/man3/strncmp.3.html
http://man7.org/linux/man-pages/man3/strncasecmp.3.html
https://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings

大小写不敏感的比较
https://stackoverflow.com/questions/5820810/case-insensitive-string-comp-in-c

EndsWith 结尾比较
https://stackoverflow.com/questions/744766/how-to-compare-ends-of-strings-in-c

StartsWith 开头比较
https://stackoverflow.com/questions/15515088/how-to-check-if-string-starts-with-certain-string-in-c
https://stackoverflow.com/questions/4770985/how-to-check-if-a-string-starts-with-another-string-in-c

=END=

, ,

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注