又过了好多天没有写这个系列了,哎,懒惰啊!今天太郁闷了,早上骑车上班时,被一辆小车突然打开的车门给绊倒了,还摔得不轻!
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类是很方便的事情。