【问题标题】:Reversing a two dimensional character array in C在C中反转二维字符数组
【发布时间】:2015-06-28 09:14:59
【问题描述】:

我正在尝试编写一个程序来反转整个字符串,并且还可以打印多次反转字符串中的每个单词。 例如我的字符串是: "2 狐狸跳过了那只懒狗。” 为此,输出应为: .god .god yzal yzal eht eht revo revo spmuj spmuj xoF xoF。 我试图将每个单词存储在二维数组中,然后反转每个单词,但我无法做到这一点。 这是我的代码。好心的帮助 注意:我们如何在控制台中提供 EOF

#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;
}

【问题讨论】:

  • 要在 Windows 上发送 EOF - 按 Ctrl+Z。要在类 Unix 系统上发送 EOF - 按 Ctrl+D。
  • 在 Windows 上不是 Ctrl+M 吗?

标签: c string


【解决方案1】:

您的代码有一些更改,请查看 cmets 以获得解释。

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;

}

【讨论】:

  • 我认为string[0]被用作输出计数而不是打印。
【解决方案2】:

代码中的更正:

  1. C 字符串以 null 结尾,但您使用换行符 \n 字符终止字符串,这是错误的。
  2. 您将空格与字符串一起存储,在这种情况下反转会很困难。
  3. 您的打印语句不会反转字符串,而是逐字符打印。

对于你需要的输出,你可以考虑这个代码。

#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;
}

输入

2 Fox jumps over the lazy dog.

输出

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

见http://ideone.com/qaIoW9

【讨论】:

    【解决方案3】:

    如果我知道您想按照字符串中的第一个数字指定的方式将每个反转的单词 N 重复一次,那么类似以下的内容将起作用:

    #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;
    }
    

    输出

    $ ./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
    

    【讨论】:

      【解决方案4】:

      您可以尝试此代码,尽管它会反转并在不同的行中打印单词。您可以尝试更多的事情来获得所需的答案。

      ` #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;
      }`
      

      【讨论】:

      • 应该是int ch;而不是char ch;,否则不能是整数值EOF。
      • strlen(string[x]) : string[x] 不是空终止。(可能是)
      • 不推荐的回答方式....没有解释/ cmets....这样的回答鼓励复制粘贴回答!!!
      猜你喜欢
      • 1970-01-01
      • 2021-05-22
      • 1970-01-01
      • 1970-01-01
      • 2016-07-14
      • 1970-01-01
      • 1970-01-01
      • 2018-12-15
      • 1970-01-01
      相关资源
      最近更新 更多