字符串比较函数strncasecmp():比较字符串的前n个字符|字符串查找函数strstr和string.find() 查找字符串str1中是否存在与str2一样的子字符串

来源:互联网 发布:js点击显示更多 编辑:程序博客网 时间:2024/04/29 16:55

摘要:string类里,find函数的实现里用到字符串比较函数,substr函数截取子字符串时常与find函数相配合。

C语言strncasecmp()函数:比较字符串的前n个字符


头文件:#include <string.h>

定义函数:int strncasecmp(const char *s1, const char *s2, size_t n);

函数说明:strncasecmp()用来比较参数s1 和s2 字符串前n个字符,比较时会自动忽略大小写的差异。

返回值:若参数s1 和s2 字符串相同则返回0。s1 若大于s2 则返回大于0 的值,s1 若小于s2 则返回小于0 的值。

范例
  1. #include <string.h>
  2. main(){
  3. char *a = "aBcDeF";
  4. char *b = "AbCdEf";
  5. if(!strncasecmp(a, b, 3))
  6. printf("%s =%s\n", a, b);
  7. }

执行结果:
aBcDef=AbCdEf

附加:
字符串比较
   extern int strcmp(char *s1,char * s2);
   extern int strncmp(char *s1,char * s2,int n);// 比较字符串s1和s2的前n个字符。
   extern int stricmp(char *s1,char * s2);//比较字符串s1和s2,但不区分字母的大小写。
   extern int strnicmp(char *s1,char * s2,int n);//比较字符串s1和s2的前n个字符但不区分大小写。
   extern int bcmp(const void *s1, const void *s2, int n);//比较字符串s1和s2的前n个字节是否相等,如果s1=s2或n=0则返回零,否则返回非零值。bcmp不检查NULL。

   说明:当s1<s2时,返回值<0;当s1=s2时,返回值=0;当s1>s2时,返回值
>0
  
比较字符串s1和s2的结尾n个字符是否相等,没有现成的函数来实现,可以先用字符串反转函数strrev,再用stricmp函数。


参考:

http://c.biancheng.net/cpp/html/168.html

C/C++字符串查找函数

C/C++ 字符串处理函数

C++ 中string.find() 函数的用法总结


http://c.biancheng.net/cpp/biancheng/view/158.html
C++处理字符串的方法—字符串类与字符串变量

字符串搜索函数 谷歌
字符串搜索函数 c++ 谷歌
字符串比较 c++  谷歌


===============================================================================================
函数strstr

原型:const char * strstr ( const char * str1, cosnt char *str2);

            char * strstr ( char * str1, const char * str2);

参数:str1,待查找的字符串指针;

            str2,要查找的字符串指针。

说明:
在str1中查找完全匹配str2的子串,并返回指向首次匹配时的第一个元素指针。如果没有找到,返回NULL指针。

即函数strstr是用于查找在字符串str1中是否存在与str2一样的(子)字符串。

功能与函数strstr相同的函数还有:

C++ 中string.find() 函数

 说明:

1.  如果string sub = ”abc“;

              string s = ”cdeabcigld“;

     s.find(sub) , s.rfind(sub) 这两个函数,如果字符串s中存在与字符串sub完全匹配即完全一样的子字符串,才返回匹配的索引即匹配的子字符串的第一个字符在字符串s中的下标值,即:当s中含有abc三个连续的字母时,才返回当前索引。

     s.find_first_of(sub), 即查找s中第一次出现的属于字符串sub中任意字母的那个字符的索引。  s.find_first_not_of(sub),   s.find_last_of(sub),  s.find_last_not_of(sub)  这三个函数也与类似 s.find_first_of(sub),即查找s中含有sub中任意字母的索引。

2.  上述这几个string类中的函数如果没有查询到,则返回string::npos,这是一个很大的数,其值不需要知道。

参见:

C++ 中string.find() 函数的用法总结


C/C++字符串查找函数


0 0