write c program to replace the words in reverse order in a string line

26 Sep 2022 Balmiki Mandal 0 C Programming

String Manipulation in C: Reverse and Replace Words Program

"Replace the words in reverse order in a string line" means taking a given string consisting of one or more words and reversing the order of the words in the string. For example, if the original string is "Hello world, how are you?", the reversed string would be "you? are how world, Hello".

To replace the words in reverse order in a string line in C, you can use the following steps:

  1. Split the string into words using the strtok() function.
  2. Reverse the order of the words in an array.
  3. Join the reversed words back into a string using the strcat() function.

C program to replace the words in reverse order in a string line:

C Programming
#include <stdio.h>
#include <string.h>

int main() {
  char string[] = "This is a test string.";

  // Split the string into words using the strtok() function.
  char *words[10];
  int i = 0;
  char *token = strtok(string, " ");
  while (token != NULL) {
    words[i] = token;
    i++;
    token = strtok(NULL, " ");
  }

  // Reverse the order of the words in an array.
  for (int j = 0; j < i / 2; j++) {
    char *temp = words[j];
    words[j] = words[i - j - 1];
    words[i - j - 1] = temp;
  }

  // Join the reversed words back into a string using the strcat() function.
  char reversed_string[100] = "";
  for (int j = 0; j < i; j++) {
    strcat(reversed_string, words[j]);
    if (j < i - 1) {
      strcat(reversed_string, " ");
    }
  }

  // Print the reversed string.
  printf("The reversed string is: %s\n", reversed_string);

  return 0;
}

Output:

 

The reversed string is: string test a is This

Further Reading:


Implementation of strncat() in C

add source string at the end of destination string

comparing two string using strcmp and strncmp

Design a function to copy to copy string into destination string using strcpy and strncpy

how to implement implementation of strncpy in c

Design a function to calculate the length of the string using strlen

pre defined string based function

Design a function using my_strcpy and using my_strchr we need to select given char in given string

 

Enroll Now:

C-Programming From Scratch to Advanced 2023-2024] "Start Supercharging Your Productivity!"

Contact Us:

  • For any inquiries, please email us at [info@electro4u.net].
  • Follow us on insta  [ electro4u_offical_ ] for updates and tips.

Note: If you encounter any issues or specific errors when running this program, please let me know and I'll be happy to help debug them!

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.