dimanche 8 novembre 2015

Reverse word in a string

This code here is for reversing words in a string. The problem is that it only reverses the first word in the string. When I ran a trace I found that it is stopping after encountering the statement if(s[indexCount] == '\0') break;

Why the code is getting null character every time the first word is reversed even though some other character is present after the first word.

#include <iostream>
using namespace std;
int main()
{
    string s;
    char tchar;
    int indexCount=0,charCount=0,wordIndex;
    cin>>s;
    while(1){
        if(s[indexCount]==' ' && charCount==0) continue;
        if(s[indexCount]==' ' || s[indexCount]=='\0' ){
            wordIndex=indexCount-charCount;
            charCount=indexCount-1;
            while(charCount!=wordIndex && charCount>wordIndex){
                tchar=s[wordIndex];
                s[wordIndex]=s[charCount];
                s[charCount]=tchar;
                charCount--;
                wordIndex++;
            }
            if(s[indexCount] == '\0') break;
            indexCount++; charCount=0;
        }
        else{
            charCount++;
            indexCount++;
        }
    }
    cout<<"\nReveresed words in the string : \n\t"<<s<<endl;
   return 0;
}

Also I'm using while(1). Does it make this a bad code?

Aucun commentaire:

Enregistrer un commentaire