Reprinted please indicate the source: http://blog.csdn.net/ns_code/article/details/21296345
Question:
Write code to reverse a C-Style String. (C-String means that "abcd" is represented as five characters, including the null character .)
Translation:
Write code to flip a C-style string. (C-style means that "abcd" must be expressed with 5 characters. The last character is an empty character '\ 0 ')
Ideas:
The simplest way is to get the length of the string, and then a for loop, swap the characters at the corresponding positions on both sides. However, since the C-language string is emphasized here, we 'd better use '\ 0' at the end of the string in the code, so we can set two pointers pLeft and pRight, and pLeft points to the first character, pRight points to the last valid character (that is, the character before '\ 0'), and moves the two pointers to the center in sequence. As long as pLeft is smaller than pRight, the characters pointed to by the two are exchanged. Since pRight needs to be first moved to the end, the time complexity is O (n ).
Implementation Code:
/*************************************** * ************************** Description: write code to flip a C-style string. The C style means that "abcd" requires five characters, and the last character is an empty character '\ 0 '. Date: *************************************** * *************************/# include <stdio. h>/* switch two characters */void swap (char * a, char * B) {* a = * a + * B; * B = * a-* B; * a = * a-* B;}/* reverse string */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 () {// note that it cannot be defined as char * str = "thanks". // This Is A String constant and cannot be modified. Char str [] = "thanks"; reverse (str); puts (str); return 0 ;}
Test results: