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:

  1. 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...

    ReplyDelete
  2. 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;
    }

    ReplyDelete
  3. 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

    ReplyDelete
  4. 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();
    }

    ReplyDelete
  5. 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

    ReplyDelete
  6. 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

    ReplyDelete
  7. 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..!

    ReplyDelete
  8. 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");
    }

    ReplyDelete
  9. 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;
    }

    ReplyDelete
  10. 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;
    }

    ReplyDelete
  11. 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

    ReplyDelete
  12. 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

    ReplyDelete
  13. 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;
    }

    ReplyDelete
  14. 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?

    ReplyDelete
  15. This comment has been removed by the author.

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

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

    ReplyDelete
  17. 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]);
    }
    }

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

    ReplyDelete
  19. #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

    ReplyDelete
  20. 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");

    }

    ReplyDelete
  21. #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;
    }

    ReplyDelete
  22. 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);
    }

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

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

    return src;
    }

    ReplyDelete
  24. 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();
    }

    ReplyDelete
  25. How the first method (recursive) works?

    ReplyDelete
  26. How method 1 (recursive) works?

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

    ReplyDelete
  28. 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

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


    my homepage calculate waist to Height ratio

    ReplyDelete
  30. Η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

    ReplyDelete
  31. 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

    ReplyDelete
  32. 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

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

    ReplyDelete
  34. 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

    ReplyDelete
  35. 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/

    ReplyDelete
  36. 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

    ReplyDelete
  37. 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

    ReplyDelete
  38. 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

    ReplyDelete
  39. 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

    ReplyDelete
  40. 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

    ReplyDelete
  41. 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

    ReplyDelete
  42. 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

    ReplyDelete
  43. 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

    ReplyDelete
  44. 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());

    ReplyDelete