字符串反转C++实现源码(带测试用例)
2013-04-26 09:37
621 查看
将字符串字符顺序反转:
参考了《剑指Offer》中的实现。
#include <iostream> using namespace std; void Reverse( char *pBegin, char *pEnd ) { if( pBegin == NULL || pEnd == NULL ) return; while( pBegin < pEnd ) { char tmp = *pBegin; *pBegin = *pEnd; *pEnd = tmp; pBegin++, pEnd--; } } void Test( char *testName, char *input, char *expectedResult ) { if( testName != NULL) cout << testName << " begins: " << endl; if( input == NULL ) return; char *pBegin = input; char *pEnd = input; //暂时 while( *pEnd != '\0' ) pEnd++; //pEnd此时已经指向'\0'了,退一个,指向最后一个字母 pEnd--; //另外一种方法得到pEnd //pEnd = pEnd + strlen(input) - 1; cout << "反转前:" << input << endl; Reverse( pBegin, pEnd ); cout << "反转后:" << input << endl; if( (input == NULL && expectedResult == NULL) || (input != NULL && strcmp(input, expectedResult) == 0) ) cout << "通过!" << endl; else cout << "失败!" << endl; } void TestReverse0() { // char input[] = "lfz"; char expected[] = "zfl"; Test( "One word", input, expected ); } void TestReverse1() { char input[] = ""; char expected[] = ""; Test( "Empty", input, expected ); } void TestReverse2() { Test( "NULL", NULL, NULL ); } void TestReverse3() { char input[] = "i am a student."; char expected[] = ".tneduts a ma i"; Test( "A sentence", input, expected ); } void TestReverse4() { char input[] = " "; char expected[] = " "; Test( "One Blanks", input, expected ); } void TestReverse5() { char input[] = " "; char expected[] = " "; Test( "Three Blanks", input, expected ); } void main() { // TestReverse0(); TestReverse1(); TestReverse2(); TestReverse3(); TestReverse4(); TestReverse5(); system( "PAUSE"); }
参考了《剑指Offer》中的实现。
相关文章推荐
- 反转指向字符串反转C++实现源码(带测试用例)
- 【C++】用C或C++实现void reverse(char* str)函数,即反转一个null结尾的字符串
- 算法题 用C或C++实现void reverse(char* str)函数,即反转一个null结尾的字符串
- CI1.2 用c或c++实现void reverse(char* str)函数,即反转一个null结尾的字符串
- C++实现链表的进本操作及测试用例
- 自己实现的C++智能指针的功能代码和测试用例
- 【代码】C++实现广义表及其测试用例
- 【代码】C++实现二叉树基本操作及测试用例
- C/C++面试程序题(一)——字符串反转、链表反转的递归、非递归实现
- C++笔试题之实现字符串反转
- 【代码】C++实现二叉树基本操作及测试用例
- 使用C/C++实现对字符串的反转(递归和非递归)
- C++实现链表的进本操作及测试用例
- c 实现字符串反转(参考redis源码)
- C++实现链表的基本操作及测试用例
- c++已经实现的2种字符串反转函数
- C++代码实现梯度下降算法并给出测试用例
- C++实现字符串反转
- C++面试题,不使用临时变量实现字符串反转
- 用C++实现void reverse(char* str)函数,即反转一个null结尾的字符串.