转载请注明出处:http://blog.csdn.net/ns_code/article/details/21296345
题目:
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个字符来表示,最后一个字符为空字符‘\0‘)
思路:
最简单的方法当然是取得字符串的长度,而后一个for循环,交换左右两边对应位置上的字符。但这里题目既然强调了C语言风格的字符串,我们最好在代码中利用到字符串末尾的‘\0‘,这样我们可以设置两个指针pLeft和pRight,pLeft指向首符,pRight指向最后一个有效字符(即‘\0‘前面的字符),向中间依次移动两指针,只要pLeft小于pRight,就交换二者指向的字符。由于要将pRight先移动到最后,因此时间复杂度为O(n)。
实现代码:
/**************************************************************** 题目描述: 编写代码,实现翻转一个C风格的字符串的功能。 C风格的意思是"abcd"需要用5个字符来表示,最后一个字符为空字符‘\0‘。 Date:2014-03-15 *****************************************************************/ #include<stdio.h> /* 交换两字符 */ void swap(char *a,char *b) { *a = *a + *b; *b = *a - *b; *a = *a - *b; } /* 反转字符串 */ void reverse(char *str) { if(!str) return; char *pLeft = str; char *pRight = str; while(*pRight != ‘\0‘) pRight++; pRight--; while(pLeft < pRight) swap(pLeft++,pRight--); } int main() { //注意这里不能定义为 char *str = "thanks", //这样定义的是字符串常量,不可修改。 char str[] = "thanks"; reverse(str); puts(str); return 0; }
测试结果:
【CareerCup】 Arrays and Strings—Q1.2,布布扣,bubuko.com
【CareerCup】 Arrays and Strings—Q1.2
原文:http://blog.csdn.net/ns_code/article/details/21296345