【CareerCup】 Arrays and Strings—Q1.2

來源:互聯網
上載者:User

轉載請註明出處: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;}

    測試結果:




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.