[CareerCup] Arrays and Strings-Q1.2

Source: Internet
Author: User

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:




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.