top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to swap the first and last word of a string without using additional array or string functions in C?

+3 votes
3,137 views

e.g. Suppose I enter a string : Ram and Shyam likes Ramesh then the output should be Ramesh and Shyam likes Ram.
Here first word Ram is swapped with Ramesh .

posted Sep 2, 2014 by Shani Verma

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void reverseStr(char *input,int start,int end);
int main()
{
   char *input=NULL;
   int length=100, end=0, start=0, error=0;

   input = (char *) malloc (length + 1);
   if(input == NULL)
   {
      printf("malloc error\n");
      exit(1);
   }

   printf("Please give the input string\n");
   error=getline(&input,&length,stdin);
   if(error == -1)
   {
      printf("error in getline\n");
      exit(1);
   }

   length=strlen(input);
   input[length-1]='\0';
   end=length-2;
   printf("Currently the string:[%s]\n",input);

   reverseStr(input,start,end);/*reverse the string*/

   for(start=0;start < end; )/*Finds the points of first and last word*/
   {
      if( input[start] != ' ' )
      {
         start++;
      }

      if( input[end] != ' ' )
      {
         end--;
      }

      if( (input[start] == ' ') && (input[end]== ' '))
      {
         break;
      }
   }

   reverseStr(input,start+1,end-1);/*reverse the string without last and first word*/
   reverseStr(input,0,start-1);/*reverse the string first word*/
   reverseStr(input,end+1,length-2);/*reverste the last letter*/
   printf("Now the string:[%s]\n",input);
   free (input);
   return 0;
}

void reverseStr(char *input,int start,int end)
{
   char temp;
   while(start<end)
   {
      temp=input[end];
      input[end]=input[start];
      input[start]=temp;
      start++;
      end--;
   }
   return;
}
answer Sep 2, 2014 by Double S
Similar Questions
+1 vote

char *p="India";
char t[10]="USA";

after the swap t should contain India and p as USA.

+8 votes

For example, 00000001 11001100 becomes 11001100 00000001;

unsigned short swap_bytes(unsigned short x) {

}

...