I have written the following code to reverse the individual words in a string. This code works like a charm and generates the required output; the only caveat being it appends a blank space at the end of the original string. E.g.: if the original string is abcd efgh then the output would be dcba hgfe.
class Solution {
public:
string rev(string& str) {
int left=0, right=str.size()-1;
while(left<right) {
swap(str[left], str[right]);
left++;
right--;
}
return str;
}
string reverseWords(string s) {
string result = "";
string str;
stringstream iss(s);
while(iss>>str) {
result+=rev(str);
result+=" ";
}
//Removing last space added at the end of the string
result[result.size()-1]=result[result.size()];
return result;
}
};
I am aware why this extra spaces crops up. This answer also represented how to overcome it. But I am doing it in the following way:
result[result.size()-1]=result[result.size()];
By this, I intend to overwrite the terminating space with the NULL character \0. But is it correct? I am doubtful because I think I am accessing an element that is out of bounds. Could someone please confirm?
Thank you!
Aucun commentaire:
Enregistrer un commentaire