一天一个CRT函数 strchr

又过了好多天没有写这个系列了,哎,懒惰啊!今天太郁闷了,早上骑车上班时,被一辆小车突然打开的车门给绊倒了,还摔得不轻!

strchr

1.介绍

MSDN上给出的解释是,找出字符串中指定的字符,返回第一个找到的字符位置的指针(即地址),如果没有找到则返回NULL。

   1: /***
   2: char *strchr(string, chr) - search a string for a character
   3:     
   4: Purpose:
   5:        Searches a string for a given character, which may be the
   6:            null character '/0'.
   7: Entry:
   8:        char *string - string to search in
   9:            char chr     - character to search for
  10:     
  11: Exit:
  12:        returns pointer to the first occurence of c in string
  13:            returns NULL if chr does not occur in string
  14: ***/
  15: template<typename T> 
  16: inline tChar *tStrChr(tChar *pStr, T chr)
  17: {
  18:     while( *pStr && *pStr != chr )
  19:         ++pStr;
  20:  
  21:     if( *pStr == chr )
  22:         return(pStr);
  23:  
  24:     return 0;
  25: }

很简单,就是循环遍历字符串,然后与指定的字符相比较。

2.测试

   1: tChar  ch = _T('r');
   2:  
   3:     tChar string[] = _T("The quick brown dog jumps over the lazy fox");
   4:  
   5:     // Search forward. 
   6:     tChar *pdest = CY_CRT::tStrChr( string, ch );
   7:     int result = (int)(pdest - string + 1);
   8:  
   9:     if ( pdest != NULL )
  10:         wcout << _T("Result:   first ") << ch << _T(" found at position ") << result << endl;
  11:     else
  12:         cout << "Result: " <<  result << "found/n";

3.兄弟函数

strrchr,这就是strchr的兄弟,不过却是反向寻找字符串中指定字符

   1: template<typename T> 
   2: inline tChar *tStrRChr(tChar *pStr, T chr)
   3: {
   4:     tChar *pStart = pStr;
   5:  
   6:     while(*pStr++)                     
   7:         ;
   8:     while(--pStr != pStart && *pStr != chr)
   9:         ;
  10:  
  11:     if( *pStr == chr )            
  12:         return pStr;
  13:  
  14:     return 0;
  15: }

说明:先找到把指定的字符串的结尾,然后倒序遍历字符串与指定字符的比较。

3.总结

我还是喜欢用C++标准库提供的模板函数(可以配合容器,当然数组也是容器的一个特化),上述的功能对应了STL提供的find_first_of,配合reverse_iterator就是反向查找(strrchr)。而string提供了find_last_of方法,所以字符串操作用string类是很方便的事情。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值