简体   繁体   中英

Reversing a two dimensional character array in C

i am trying to write a program which reverses a entire string and also may print reversing each word of the string more than one time. For example my string is: "2 Fox jumps over the lazy dog." for this, the output should be: .god .god yzal yzal eht eht revo revo spmuj spmuj xoF xoF. I am trying to store each word in a 2d array and then reverse each word but i am not able to do that. here is my code. kindly help Note: how do we provide EOF in console

#include <stdio.h>
#include <stdlib.h>

int main() {
    char string[100][100];
    char ch;
    int i = 0, j = 0, l = 0, count = 0, x = 0, y = 0;
    while ((ch = getchar()) != EOF) {
        string[i][l++] = ch;
        if (ch == ' ') {
            string[i][l] = '\n';
            i++;
            l = 0;
            count++;
        }
    }
    for (x = 0; x <= count; x++) {
        int length = strlen(string[x]) - 1;
        for (y = length; y >= 0; --y)
            printf("%s", string[y]);
    }
    return 0;
}

Here are a few changes to your code check the comments for explanation.

int main()
{    
char string[100][100];
char ch;
int i=0,j=0, l=0, count=0, x=0, y=0;
while((ch=getchar())!=EOF)
{
    string[i][l++] = ch;
    if(ch==' ')
     {
       string[i][l] = '\0';    //make the string null terminated otherwise you cant work with its length
       i++;
       l=0;
       count++;
    }
}
string[i][l]='\0';    //make the last string null terminated
for(x=count; x>=0; x--)        //read from last counter 
{
   int length = strlen(string[x])-1;
   for(y=length; y>=0; --y)
   {
      printf("%c", string[x][y]);       //print by each character and not string.
   }
}
return 0;

}

Corrections in your code:

  1. C strings are null terminated, but you are terminating your strings with newline \\n character, which is wrong.
  2. You are storing the whitespace with the string, reversing will be difficult in this case.
  3. Your print statement won't reverse the string, print it character by character.

For the output that you need, you can consider this code .

#include <stdio.h>
#include <stdlib.h>

int main() {
    char string[100][100];
    char ch;
    int i = 0, j = 0, l = 0, count = 0, x = 0, y = 0;
    while ((ch = getchar()) != EOF) {
        if (ch == ' ') {
            string[i][l] = '\0';    /// Null terminate the string
            i++;
            l = 0;
            count++;
        }
        else
            string[i][l++] = ch;   /// Don't add whitespace to the string
    }
    string[i][l] = '\0';
    for (x = count; x >= 0; x--) {
        int length = strlen(string[x]) - 1;
        for (y = length; y >= 0; --y)
            printf("%c", string[x][y]);   /// Print the string in reverse
        printf(" ");
        for (y = length; y >= 0; --y)
            printf("%c", string[x][y]);   /// Twice
        printf(" ");
    }
    return 0;
}

Input

2 Fox jumps over the lazy dog.

Output

.god .god yzal yzal eht eht revo revo spmuj spmuj xoF xoF 2 2 

See http://ideone.com/qaIoW9

If I understand you want to duplicate each reversed word N times as specified by the first number in the string, then something like the following would work:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *strrevdup (char* str);

int main (int argc, char **argv) {

    if (argc < 2 ) {
        fprintf (stderr, "error: insufficient input, usage: %s \"# string\"\n", 
                argv[0]);
        return 1;
    }

    char *str = strdup (argv[1]);
    char *p = str;
    char *rev = NULL;
    int mult = 0;
    int i = 0;

    while (*p && *p != ' ') p++;
    *p = 0;
    mult = atoi (str);
    *p = ' ';
    if (!mult) return 1;
    while (*p && *p == ' ') p++;

    rev = strrevdup (p);
    char *r = rev;

    printf ("\n the reversed string with duplicated words '%d' times is:\n\n", mult);
    for (p = strtok (r, " "); p; p = strtok (NULL, " \n"))
        for (i = 0; i < mult; i++)
            printf (" %s", p);
    printf ("\n\n");

    free (str);
    free (rev);

    return 0;
}

/** strrevdup - reverse duplicate string, swaps src & dest each iteration.
*  Takes valid string, duplicates and reverses, original is preserved.
*  Returns pointer to reversed string on success, NULL otherwise.
*  Requires string.h, caller is responsible for freeing memory allocated.
*/
char *strrevdup (char* str)
{
    if (!str) {
        printf ("%s() error: invalid string\n", __func__);
        return NULL;
    }

    char *rstr = strdup (str);
    char *begin = rstr;
    char *end = rstr + strlen (rstr) - 1;
    char tmp;

    while (end > begin){
        tmp=*end;
        *end-- = *begin;
        *begin++ = tmp;
    }

    return rstr;
}

Output

$ ./bin/strrevndup "2 Fox jumps over the lazy dog."

 the reversed string with duplicated words '2' times is:

 .god .god yzal yzal eht eht revo revo spmuj spmuj xoF xoF

you may try this code although it will reverse and print words in different lines.. you may try few more things to get the desired answer.

` #include <stdio.h>
  #include <stdlib.h>
  #include<string.h>
  int main()
  {
   char string[1024][1024];
   char ch;
   int t,z;
   scanf("%d",&t);
   z=t;
   int i=0, l=0, count=0, x=0, y=0;
   getchar();
   while((ch=getchar())!=EOF)
    {
     if(ch=='\n')
      {
        i++;
        l=0;
        count++;
        string[i][l++] = ch;
        i++;
        l=0;
      }
     else if(ch==' ')
     {
       i++;
       l=0;
       count++;
     }
     else{
        string[i][l++] = ch;
         }
  }
  for(x=count+1; x>=0; x--)
   {
     if(string[x][0]=='\n')
     {
       printf("\n");
     } 
   else{
        char *rev=strrev(string[x]);
        while(t--)
        printf("%s ",rev);
        t=z;
        }
     }
     return 0;
}`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM