String Reverse in C

String Reverse Program in C
String reverse can be done in multiple ways in C Language. Please find some samples below



Method 1 : Reverse String using Array in C
#include< stdio.h >
#include< string.h >
int main(){
char ch2[10],ch1[10]=”Linux”;
int i,j,k;
i=strlen(ch1);
k=i;
for(j=0;ch2[j]=ch1[i-1];++j,–i);
printf(“\nReverse String is %s”,ch2);
return 0;
}
Method 2 : String Reverse using Array in C
#include< stdio.h >
#include< string.h >
int reverse(int i);Method 3: Print String in reverse order in C
char str[]=”Welcome to TechPages”;
int main()
{
printf(“\nThe string is: %s”, str);
reverse(0);
printf(“\nReversed string is: %s”, str);
return 0;
}

int reverse(int i) {
    char c;
    while (i<=(strlen(str)/2)) {
        c= str[i];
        str[i]=str[strlen(str)-i-1];
        str[strlen(str)-i-1]=c;
        i++;
        }
return 0;
}
Method 3 : String Reverse using printf
#include < stdio.h >
void rev_str(char* str){
if(*str != ‘\0’)
rev_str(str+1);
printf(“%c”,*str);
}
int main(){
rev_str(“HelloWorld”);
return 0;
}
Method 4: String Reverse using recursion in C
#include< stdio.h >
#include< string.h >
char* reverse(char *s,int start,int last){
char temp;
if(start>=last){
return s;
}
else{
temp = s[start];
s[start]=s[last];
s[last]=temp;
reverse(s,start+1,last-1);
}
}
int main(){
char s[]=”visha”;
reverse(s,0,strlen(s)-1);
printf(“\n ====> %s lenght : %d “,s,strlen(s));
return 0;
}

About mohan

This is Mohan Jayapalan author of TechPages Blog.I am a part time blogger and Currently working for private Software Concern.

© Copyright 2010-2016 www.techpages.org · All Rights Reserved · Powered by WordPress ·