Saturday, July 7, 2007

Write a C program to reverse a string.

There are a number of ways one can reverse strings. Here are a few of them. These should be enough to impress the interviewer! The methods span from recursive to non-recursive (iterative).

Also note that there is a similar question about reversing the words in a sentence, but still keeping the words in place. That is


I am a good boy


would become


boy good a am I


This is dealt with in another question. Here I only concentrate on reversing strings. That is


I am a good boy


would become


yob doog a ma I



Here are some sample C programs to do the same


Method1 (Recursive)


#include

static char str[]="STRING TO REVERSE";

int main(int argc, char *argv)
{
printf("\nOriginal string : [%s]", str);

// Call the recursion function
reverse(0);

printf("\nReversed string : [%s]", str);
return(0);
}

int reverse(int pos)
{
// Here I am calculating strlen(str) everytime.
// This can be avoided by doing this computation
// earlier and storing it somewhere for later use.

if(pos<(strlen(str)/2))
{
char ch;

// Swap str[pos] and str[strlen(str)-pos-1]
ch = str[pos];
str[pos]=str[strlen(str)-pos-1];
str[strlen(str)-pos-1]=ch;

// Now recurse!
reverse(pos+1);
}
}





Method2


#include
#include
#include

void ReverseStr ( char *buff, int start, int end )
{
char tmp ;

if ( start >= end )
{
printf ( "\n%s\n", buff );
return;
}

tmp = *(buff + start);
*(buff + start) = *(buff + end);
*(buff + end) = tmp ;

ReverseStr (buff, ++start, --end );
}


int main()
{
char buffer[]="This is Test";
ReverseStr(buffer,0,strlen(buffer)-1);
return 0;
}




Method3


public static String reverse(String s)
{
int N = s.length();
if (N <= 1) return s;
String left = s.substring(0, N/2);
String right = s.substring(N/2, N);
return reverse(right) + reverse(left);
}





Method4

for(int i = 0, j = reversed.Length - 1; i < j; i++, j--)
{
char temp = reversed[i];
reversed[i] = reversed[j];
reversed[j] = temp;
}
return new String(reversed);





Method5


public static String reverse(String s)
{
int N = s.length();
String reverse = "";
for (int i = 0; i < N; i++)
reverse = s.charAt(i) + reverse;
return reverse;
}





Method6

public static String reverse(String s)
{
int N = s.length();
char[] a = new char[N];
for (int i = 0; i < N; i++)
a[i] = s.charAt(N-i-1);
String reverse = new String(a);
return reverse;
}





Isn't that enough?

56 comments:

Anonymous said...

awesome work.. btw for application of reverse link list... it can be used to check if a string stored in link list char by char is palindrome or no.. so half list we traverse by reverse recursion and half normally n compare values... may b u can post this question as well...

Anonymous said...

char* strReverse(char* str)
{
int i=0, j=0;
while(str[j] != '\0')
j++;
j--;
while(i<=j){
char t = str[i];
str[i++] = str[j];
str[j--] = t;
}
return str;
}

sumeet-questions&Answers said...

I tried to work on this and found smallest code snippest to reverse a string as below:

#include

void rev ( char*, char* );

int main (int argc, char* argv[])
{
char buf[]="Sumeet C-Linux 1984";

char *end;

// In this end will traverse through whole sting and get pointer at end of sting.
for(end=buf; *end; end++);

rev(buf, end-1);

printf(" Reversed String : %s\n",buf);

return 0;
}

void rev (char *str, char *end)
{
char t;

while (str < end)
{
t = *str;
*str++ = *end;
*end-- = t;
}
}

sumeet@sumeetubuntupc:~/test-codes$ ./reverse_strg.o
Reversed String : 4891 xuniL-C teemuS

sandy said...

How about using a stack?

stack<char> tstack;
int i = 0;

while(str[i] != 0x0)
tstack.push(str[i++]);
i = 0;
while(i < tstack.size()+1)
{
str[i++] = tstack.top();
tstack.pop();
}

Anonymous said...

Hi guy. I am only I start to study c programs
c program tutorial.
I have visited a site http://program.v3host.be/?cat=204.
Much to our regret I have very little found out about it.
You can probably tell to me a good site about c programming.
I will be very glad.
Thansk

Anonymous said...

Greetings guy. I am only I start to study c program array.
I have visited a site http://program.v3host.be/?cat=204.
Much to our regret I have very little found out about it.
You can probably tell to me a good site about c program array.
I will be very glad.
Thansk

Anonymous said...

can u temme if the foll code is right..??
#include
#include
main()
{char a[10],b[10];
int l;
printf(""enter the string to be reversed");
scanf("%s",a);
l=strlen(a);
int i;
for(i=0;i<l;i++)
strcpy(b[i],a[l-i]);
printf("the reversed string is %s",b);
}
please help me..!

Anonymous said...

This is how it should look like

#include
#include
main()
{
char a[10],b[10];
int i;
int l;
printf("enter the string to be reversed");
scanf("%s",a);
l=strlen(a);
for(i=0;i<l;i++)
b[i] = a[l-1-i];
b[i] = '\0';
printf("the reversed string is %s",b);
system("PAUSE");
}

monica said...

Hey you can try this. It works fine:

#include
#include
int main()
{
char str[10],newstr[10];
int length,i,k;

printf("enter your string to reverse>>");
scanf("%s",str);

length=(strlen(str)-1);

for(i=0;i<=length;i++)
{
newstr[i]=str[length-i];

}
newstr[length+1] = '\0';
k=strlen(newstr);

printf("\n Original String is: %s \n Reverse string is: %s",str,newstr);
printf("\n new string length is: %d",k);

getch();
return 0;
}

monica said...

One more solution to reverse string

#include
#include
int main()
{
char str[50],newstr[50];
int length,i,k;

printf("enter the string>>");
scanf("%s",str);
length=(strlen(str)-1);

for(i=0,k=length;i<=length;i++,k--)
{
newstr[k]=str[i];

}
newstr[length+1] = '\0';
k=strlen(newstr);

printf("\n Original String is: %s \n Reverse string is: %s",str,newstr);
printf("\n new string length is: %d",k);
getch();
return 0;
}

Kevin John said...

strrev ???

Anonymous said...

tried one...

int
reverse(int pos)
{
int strl = strlen(str)-1,i;
int substrstart = 0,substrend = 0;

char temp;
for(;;)
{
if( pos <= strl/2){
temp = str[pos];
str[pos]= str[strl-pos];
str[strl-pos] = temp;
}
else
break;
pos++;
}
for(;substrend-1 <= strl;)
{
if(str[substrend] == ' ' || str[substrend] == '\0')
{
for(i = 0; i <= ((substrend-1) - substrstart)/2; i++)
{
temp = str[substrstart+i];
str[substrstart+i] = str[(substrend-1)-i];
str[(substrend-1)-i] = temp;
}
if(str[substrend] == '\0')
{
break;
}
substrstart=substrend+1;
}
substrend++;
}
return 0;
}

Thanks

Anonymous said...

Hi Guys... to post full prog ... previous of mine...

#include "stdio.h"
#include "stdlib.h"

char str[20]="Hi wise hungry boy";

int
reverse(int pos)
{
int strl = strlen(str)-1,i;
int substrstart = 0,substrend = 0;

char temp;
for(;;)
{
if( pos <= strl/2){
temp = str[pos];
str[pos]= str[strl-pos];
str[strl-pos] = temp;
}
else
break;
pos++;
}
for(;substrend-1 <= strl;)
{
if(str[substrend] == ' ' || str[substrend] == '\0')
{
for(i = 0; i <= ((substrend-1) - substrstart)/2; i++)
{
temp = str[substrstart+i];
str[substrstart+i] = str[(substrend-1)-i];
str[(substrend-1)-i] = temp;
}
if(str[substrend] == '\0')
{
break;
}
substrstart=substrend+1;
}
substrend++;
}
return 0;
}
void
main(int argc, char **argv)
{
printf("before string reverse: \n%s\n",str);
reverse(0);
printf("after string reverse: \n%s\n",str);
}



results below

before string reverse:

Hi wise hungry boy

after string reverse:

boy hungry wise Hi

codecaine_21 said...

Here is a small efficient way...

#include
#include

int main(void)
{
int i;
char str[50];

printf("Please enter a small sentence to be reversed: ");
fgets(str, sizeof(str), stdin);
//fgets adds a newline
//char at the end of the string.

for(i=strlen(str); i>-1; i--)
printf("%c", str[i]);
printf("\n");

return 0;
}

Anonymous said...

I'm considering performing a reverse mobile phone investigation by going online. I'm getting all of these calls by someone that I don't know and am concerned who they think they're contacting. All sorts of strange texting and messages are being left on my personal voice mail and its beginning to drive me insane. And so, exactly where can i locate these reverse cellphone lookup web sites?

Unknown said...
This comment has been removed by the author.
Anonymous said...

Good Job!
Here is another nice post addressing the same question.

http://puddleofriddles.blogspot.com/2011/04/reverse-string.html

Aditya said...

Hi

Another short crisp way to do would be something like this

void reverse(string &s)
{
size_t begin=0;
size_t end=s.length();
while(begin!=end && begin!=--end)
{
swap(s[begin++],s[end]);
}
}

neethu said...

thank you.......

vanilee said...

thanks!

Anonymous said...

void StrReverse4(char *str)
{
if(*str)
{
StrReverse4(str+1);
putchar(*str);
}
}

Nidhindas.k.p said...

#include
#include
main()
{
char str[50],revstr[50];
int i=0,j=0;
printf("Enter the string to be reversed : ");
scanf("%s",str);
for(i=strlen(str)-1;i>=0;i--)
{
revstr[j]=str[i];
j++;
}
revstr[j]='\0';
printf("Input String : %s",str);
printf("\nOutput String : %s",revstr);
getch();
}
hws it

Anonymous said...

here is the program in c to reverse the string using pointer



#include
#include
void main()
{
char str[]="rohit kumar singh";
char *p;
p=&str;
char *q;
q=p;
int s=strlen(str);
p=p+s;
while(p!=q-1)
{
printf("%c",*p);
p--;
}
printf("\n");

}

prashant koli said...

#include
void reverse(char *str)
{
if(*str !='\0')
{
reverse(str+1);
printf("%c",*str);
}
}

int main()
{
char s[]="i love u";
reverse(s);
return 0;
}

Nmkraj said...

int index;
char *end;
char *start;
char temp;

void
revstr(char *start, char* end)
{
char temp;
if(start < end)
{
temp = *start;
*start = *end;
*end = temp;
revstr(++start, --end);
}

}
void
main()
{
char buf[]="Sumeet C-Linux 1984";
start=buf;
end = buf;

// to move the end to last
for ( end=start;*(end+1) != '\0';end++);

revstr(start, end);

printf("%s \n", buf);
}

Anonymous said...

good job... but y don't we use this simple method....?

char* ReverseString(char *src)
{
strrev(src);

return src;
}

Uttam Agrawal said...

Sample C Program To Accept A String & Display It.

Sample C Program To Find The Length Of A String.

Sample C Program To Concatenate Two Strings.

Sample C Program To Compare Two Strings.

Sample C Program To Swap Two Strings.

Sample C Program To Swap Two Strings Using strcpy() Function.

Sample C Program To Sort A Given Number Of Strings Using strcmp() Function.

Sample C Program To Check Whether A String Is Palindrome Or Not.

Sample C Program To Print The Reverse Of A String.

Sample C Program To Join Two Strings.

Sample C Program To Display Array Of Strings.

Sample C Program To Convert String To An Integer Using atoi() Function.

Sample C Program To Accept A String & Display In Reverse.

Sample C Program To Accept A String & Display Its Alternate Characters.

Sample C Program To Accept A String & Display Alternate Characters In Either Case.

RAGHURAM said...

i m not getting corect output for the following. i m geting reverse + some other characters. i dont know why. please explain me!!!



#include
#include
char * reverse(char *s)
{
int j=strlen(s)-1,i=0;
char *t="";
printf("string = ");
puts(s);
while(j>=0)
{
t[i++]=s[j--];
}
printf("reverse = ");
puts(t);
return t;
}
void main()
{
char *s1,*s2;
clrscr();
printf("Enter a string\n");
gets(s1);
printf("string = ");
puts(s1);
strcpy(s2,reverse(s1));
printf("reverse = ");
puts(s2);
getch();
}

Anonymous said...

How the first method (recursive) works?

Anonymous said...

How method 1 (recursive) works?

Anonymous said...

A nice article to reverse is at http://www.ritambhara.in/recursive-function-to-reverse-a-string/

Anonymous said...

thanxs guyz

Anonymous said...

continuously i used to read smaller content that as well clear their
motive, and that is also happening with this piece of writing which I am reading now.



Visit my web site - diets that work

Anonymous said...

What a data of un-ambiguity and preserveness of
valuable familiarity about unpredicted feelings.


my homepage calculate waist to Height ratio

Anonymous said...

Ηelpful info. Luсkу me I founԁ your sіte by аccіdent, and I аm surpгiѕeԁ why this accіdеnt ԁid nοt took place
in аdvance! I bookmarked it.

My blog post: abrir cuenta facebook

Anonymous said...

I’m not that much оf a online reаdеr to be honest but your sites rеally niсe, keep it up!
I'll go ahead and bookmark your website to come back in the future. All the best

Also visit my webpage - facebook cuenta gratis

Anonymous said...

Wοw, this poѕt iѕ good, my younger sister іs
analyzing thеse things, thus I am going to tell
heг.

My websіte; www.ihma.in

sanjay said...

Appreciation for nice Updates, I found something new and folks can get useful info about BEST ONLINE TRAINING

Anonymous said...

Greаt pοst. I waѕ checking сonstantlу thiѕ weblog
and I am inspіreԁ! Verу usеful іnfогmation particulагlу the ultimate part :) Ι ԁeal with ѕuch іnformatiοn a lot.
ӏ was looking for this partісular info fοr
a long tіme. Thаnk yоu anԁ best of luck.


Revieω my web blog :: facebook cuenta gratis

Anonymous said...

Another great post! Just wondering if anybody
has any any links or screenshots of good Email Templates in practice?

It is usually good to see templates, another thing to see examples to benchmark as good
communication. Will be willing to see any links.



My website; http://beautifulemails.com/email-templates-free/

Anonymous said...

It's really very complicated in this full of activity life to listen news on TV, so I just use web for that purpose, and obtain the most recent information.

My web page email templates in outlook 2010

Anonymous said...

I do agree with all of the ideas you have offered in your post.

They're really convincing and can definitely work. Still, the posts are very short for newbies. May you please extend them a little from subsequent time? Thank you for the post.

Visit my blog post :: bengali bridal makeup

Anonymous said...

I every time used to read paragraph in news papers but now as I am a user of internet therefore from
now I am using net for posts, thanks to web.

Also visit my website ... email newsletters templates

Anonymous said...

Heya! I just wanted to ask if you ever have any
issues with hackers? My last blog (wordpress) was hacked and I ended up losing several weeks
of hard work due to no back up. Do you have
any methods to protect against hackers?

My page: Email templates

Anonymous said...

I am really enjoying the theme/design of your web site. Do you ever run into
any browser compatibility issues? A number of my blog visitors have complained about my site not operating correctly in
Explorer but looks great in Opera. Do you have any tips to
help fix this problem?

Here is my weblog - email Announcement templates

Anonymous said...

Hello there, just became aware of your blog through Google, and found that it's truly informative. I am gonna watch out for brussels. I will appreciate if you continue this in future. A lot of people will be benefited from your writing. Cheers!

My web page all natural skin care

Anonymous said...

Howdy, i read your blog from time to time and i own a similar one and i was just curious if you get a lot of spam remarks?

If so how do you prevent it, any plugin or anything you can recommend?
I get so much lately it's driving me mad so any help is very much appreciated.

My web page: mouse click the next internet Page

Anonymous said...

If you are going for finest contents like I do, just visit this site daily since it presents quality contents, thanks

My web site - Highly recommended Site

Anonymous said...

Console.WriteLine("Pleae enter a string, print enter to end");
string input = Console.ReadLine();
StringBuilder sb = new StringBuilder();
int i = input.Length-1;
while (i != - 1)
{
sb.Append(input[i--]);
}
Console.WriteLine("Reverse stirng is " + sb.ToString());

AJIT MULIK said...

You can get a new approach for this program at C PROGRAMS WITH EASY APPROACH

AJIT MULIK said...

A New and Easy approach for this Program And More than 1000 C Program Click here to visit C Program Hub.

yanmaneee said...

hermes handbags
balenciaga speed
kyrie 4
michael kors outlet
balenciaga shoes
nike shox
yeezy
moncler jacket
pg 4
golden goose

Unknown said...

check this hop over to this site this content replica gucci Going Here the original source

Unknown said...

this high quality replica bags site here Full Article click here for info Resources

Unknown said...

why not look here more helpful hints here are the findings you could try these out see here now Extra resources

Unknown said...

j5a22l9u03 c2q47z4m08 p4h94v9o47 e3r44a6h94 g1h67l4h13 n9a02w5x22