1. 程式人生 > >C語言實現將一個字符串翻轉

C語言實現將一個字符串翻轉

spa highlight amp false main lag temp break bcd

問題: 對於字符串char* = " abcd efg h"; 要求輸出" h efg abcd "; 字符串整體翻轉,但是裏面每一個單詞的順序不翻轉

思想:<1>取得原始字符串的長度,

<2>將字符串第一個出現空格位置的索引記錄下來,並且放到一個整形數組裏,例如上面的

出現空格的位置分別是0 5 11 那麽記錄數組int b[j]; b[0]=0 b[1] =5; b[2]=11;

<3>針對每一個空格開始出現的位置,將數組b[j] 逆序輸出,例如

" h"輸出 "h "

" efg" 輸出"efg "

" abcd"輸出“abcd "

<4>將上面的輸出用strcat拼接起來就是得到的目的字符串

代碼如下:

#include <iostream>
#include <string.h>

using namespace std;

#define ARRAY_LEN 10

int main() {
    char* a="   OPKI am  test   abcdef    ";

    int len = strlen(a);
    cout<<"original---"<<a<<"---"<<endl;
    cout<<"str len is "<<len<<endl;
    int firstempty = false;
    int b[ARRAY_LEN];
    int j = 0;
    for (int i = 0; i < len; i++) {
        if (i == 0) {
            if (a[i] == ‘ ‘) {
                b[j] = 0;
                j++;
                firstempty = true;
            }
        }
        int temp = i + 1;
        if (a[i] != ‘ ‘ && a[temp] == ‘ ‘) {
            b[j] = temp;
            j++;
        }
    }

    cout<<"j is "<<j<<endl;

    cout<<"---change--";
    for (int k = j; k > 0; k--) {
        int tmp = b[k-1];
        int i = 0;
        bool flag = false;
        while(a[tmp] != ‘\0‘) {
            char ch = a[tmp];
            if (ch != ‘ ‘) {
                flag = true;
                cout<<ch;
            } else {
               if (!flag) {
                   i++;
               } else {
                   break;
               }
            }
            tmp++;
        }
        for (int t = i; t >0; t--) {
            cout<<‘ ‘;
        }
    }

    if (!firstempty) {
       cout<<*a;
       while(*(++a) != ‘ ‘)
            cout<<*a;
    }
    cout<<"---"<<endl<<"end"<<endl;
   
    return 0;
}

C語言實現將一個字符串翻轉