Write a C, C++ program to reverse words in a given string. Given an input string, we have to write a code to reverse words of a string.
Programming questions on strings
Suppose, An input string is learn programming.
Input - learn programming
Output - nrael gnimmargorp
Programming question on Arrays
Programming question on Linked List
Sorting algorithm and their time complexity
Stack implementation
Programming questions using Recursion
C, C++ interview questions
Programming Books
Programming questions on strings
Suppose, An input string is learn programming.
Input - learn programming
Output - nrael gnimmargorp
C Program to Reverse Words in a String
#include <stdio.h> #include <string.h> #include <ctype.h> int main(void) { // String declaration of max size 100 char str[100], temp; int len, i, j, k; // Input string printf("Enter a string \n"); gets(str); len = strlen(str); for(i = 0, j = 0; i < len; i++) { // If it's not a alphabet or number if(!isalnum(str[i]) || (i == len - 1)) { if (i < len - 1) { k = i - 1; } else { k = i; } //Reverse while(k > j) { temp = str[j]; str[j] = str[k]; str[k] = temp; k--; j++; } j = i + 1; } } printf("%s", str); return 0; }
C++ Program to Reverse Words in a String
#include <iostream> #include <string.h> using namespace std; int main() { char str[100], temp; int i, j, k, len; cout << "Enter a string \n"; cin.getline(str,100); len = strlen(str); for(i = 0, j =0; i < len; i++) { if(str[i]==' ' || i == len-1){ if(i < len-1) { k = i - 1; } else { k = i; } while (k > j) { temp = str[j]; str[j] = str[k]; str[k] = temp; j++; k--; } j = i + 1; } } cout << str; return 0; }
Programming question on Arrays
Programming question on Linked List
Sorting algorithm and their time complexity
Stack implementation
Programming questions using Recursion
C, C++ interview questions
Programming Books
No comments:
Post a Comment