CCI习题 1-2:Reverse C String

By | 2012 年 11 月 13 日

从0到len / 2 – 1,交换cstr[i] 和 cstr[len – 1 – i]就可以了。
交换两个值用了一个trick,就是三次异或。



Write code to reverse a C-Style String. (C-String means that “abcd” is represented as five characters, including the null character.)



代码

<

pre>
//
// main.cpp
// CCI.1.2.ReverseCString
//
// Created by Qiu Xiangyu on 12-11-13.
// Copyright (c) 2012年 Qiu Xiangyu. All rights reserved.
//

include

using namespace std;

void reverseCString(char *cstr) {
if (cstr == NULL) {
return;
}
size_t len = strlen(cstr);
for (size_t i = 0; i < len / 2; ++i) {
//swap cstr[i] and cstr[len – 1 -i]
size_t li = len – 1 – i;
cstr[i] = cstr[i] ^ cstr[li];
cstr[li] = cstr[i] ^ cstr[li];
cstr[i] = cstr[i] ^ cstr[li];
}
}

int main(int argc, const char * argv[])
{
// insert code here…
cout << “Input below:\n”;
char cstr[200];
scanf(“%s”,cstr);
cout<<“Input:”<<cstr<<endl;

//process
reverseCString(cstr);
cout<<"Revert Result : "<<cstr<<endl;

return 0;

}

发表评论

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