原文:
Write code to reverse a C-Style String. (C-String means that “abcd” is represented as five characters, including the null character.)
译文:
写代码翻转一个C风格的字符串。(C风格的意思是"abcd"需要用5个字符来表示,包含末尾的 结束字符)
这是一道经典的面试题目,虽然看似简单,但仍然有陷阱。唯一的陷阱就是空间复杂度为O(1)即原地置换,要特别注意null字符。
/********************************* * 日期:2014-05-05 * 作者:SJF0115 * 题目: C风格字符串翻转 * 来源:CareerCup **********************************/ #include <iostream> #include <stdio.h> #include <string.h> using namespace std; //C风格字符串翻转 void Reverse(char *str){ if(str == NULL){ return; } char *beg = str; char *end = str; //end指向最后一个元素 while(*end){ end++; } //注意 --end; char temp; //交换 while(beg < end){ temp = *beg; *beg = *end; *end = temp; end--; beg++; } } int main(){ char str[] = "1234567890"; Reverse(str); puts(str); return 0; }
//C风格字符串翻转 void Reverse(char *str){ if(str == NULL){ return; } int len = strlen(str); char temp; //交换 for(int i = 0;i < len / 2;i++){ temp = str[i]; str[i] = str[len-1-i]; str[len-1-i] = temp; } }
交换的进一步优化,使用异或进行交换:
//C风格字符串翻转 void Reverse(char *str){ if(str == NULL){ return; } char *beg = str; char *end = str; //end指向最后一个元素 while(*end){ end++; } //注意 --end; char temp; //异或 交换 while(beg < end){ *beg = *beg^*end; *end = *beg^*end; *beg = *beg^*end; end--; beg++; } }
CareerCup之1.2C风格字符串翻转,布布扣,bubuko.com
原文地址:http://blog.csdn.net/sunnyyoona/article/details/25029623