把一个字符串倒置,并保持其中每个单词顺序不变

int reverseStr(char* str,int begin,int end){
    char tem;
    if (str==NULL)
        return 0;
    if (begin<end){
        tem = str[begin];
        str[begin] = str[end];
        str[end] = tem;
        reverseStr(str,++begin,--end);
    }
    return 1;
}

int reverseWords(char* str){

    int wordBegin=0,wordEnd=0,len=0;
    if (str==NULL||*str=='\0')
    {
        cout<<"str is Null!"<<endl;
        return 0 ;
    }
    len = strlen(str);
    reverseStr(str,0,len-1);//首先把整个字符串整体翻转
    cout<<str<<endl;
    while (wordEnd<len){
        if (str[wordEnd]!=' '){
            wordBegin = wordEnd;
            while (str[wordEnd]!=' '&&str[wordEnd]!='\0'&&wordEnd<len){
                wordEnd++;
            }
            reverseStr(str,wordBegin,wordEnd-1);
        }
        wordEnd++;
    }
    return 1;
}

你可能感兴趣的:(编程实践)