How to reverse individual word in a long string in C, C++
Again this is one of the tricky interview question in which we have to reverse the string word by word, "not the string".
Again there may be multiple ways to do that I am mentioning one of them here in this post :
If you have any suggestions please leave a comment below.
Again there may be multiple ways to do that I am mentioning one of them here in this post :
#include <iostream> #include <conio.h> #include <string> using namespace std; void reverse_string(char *str) { int len = strlen(str) - 1; char temp; for (int i = 0; i <= len / 2; ++i) { temp = str[i]; str[i] = str[len - i]; str[len - i] = temp; } } void reverse_indiviualWords(char *str) { char *token = strtok(str, " "); string result = ""; while (token != NULL) { reverse_string(token); result += token; result += " "; token = strtok(NULL, " "); } result[result.length() - 1] = '\0'; strcpy(str, result.c_str()); } void main() { char str[] = "How to reverse a string"; cout << "Before :" << str << endl; reverse_indiviualWords(str); cout << "After :" << str << endl; _getch(); }
Links : Another way of doing the same.
Thanks for visiting.
If you have any suggestions please leave a comment below.
Comments
Post a Comment