c - 反转字符串 c 中的单词

标签 c

我正在尝试反转字符串中的单词,我刚刚开始学习 C,所以我用我所知道的东西尝试了这一点。这是代码

#include <stdio.h>

int main (void)
{
    char a[11] , b[11]  ;
    int i = 0  , j = 0 , x  , p = 0 , q =9  ;
    while ((a[j++] = getchar()) != '\n') ;
    a[10] = '\0' ;
    while (p < 11 )
    {
        b[q] = a[p] ;
        q-- ;
        p++ ;
    }

    j = 0 ;
    while (j < 10)
    {
        ++i  ;
        ++j ;
        if (a[j] == ' ' || a[j] == '\0')
        {
            for (x = j  ; x >= (j - i) ; x--)
                printf("%c" , b[x]) ;
            i = 0 ;
        }
    }
    return 0 ;
}

有一个意外的“=”。 就像我的名字是 名字=我的

请进行所需的更正。

最佳答案

如果您只想接受单个字符串,这里是代码,

#include<stdio.h>

int main()
{
   char myString[50],newString[50];
   int index1=0,index2=0,tmpIndex;

   printf("Enter a string:\n");
   scanf("%s",&myString);
   printf("Entered String:%s\n",myString);


   while(myString[index2]!= '\0')
   {
     index2=index2+1;
   }
   tmpIndex=index2;

   printf("Original String Lenght=%d\n",tmpIndex);
   printf("Reversing String....\n");

   index2=index2 - 1;//To not to copy the '\0' of original string
   while(index1 < tmpIndex)
   {
     newString[index1]=myString[index2];
     //printf("%c\n",newString[index1]);
     index1++;
     index2--;
   }
   newString[index1] = '\0';//finally at the end of string add '\0' 
   printf("\n%s",newString);
   printf("\nNew string Lenght:%d",index1);
 }

这里是接受中间有空格的字符串的代码,(只需使用fgets()而不是scanf()。)

#include<stdio.h>

int main()
{
   char myString[50],newString[50];
   int index1=0,index2=0,tmpIndex;

   printf("Enter a string:\n");
   fgets(myString,50,stdin);
   printf("Entered String:%s\n",myString);


   while(myString[index2]!= '\n')
   {
     index2=index2+1;
   }
   tmpIndex=index2;

   printf("Original String Lenght=%d\n",tmpIndex);
   printf("Reversing String....\n");

   index2=index2 - 1;//To not to copy the '\0' of original string
   while(index1 < tmpIndex)
   {
    newString[index1]=myString[index2];
    //printf("%c\n",newString[index1]);
    index1++;
    index2--;
   }
   newString[index1] = '\0';//finally at the end of string add '\0' 
   printf("\n%s",newString);
   printf("\nNew string Lenght:%d",index1);
}

关于c - 反转字符串 c 中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33087072/

相关文章:

c - 如何使用 Cgo 访问 MATLAB 数组中的值?

c - 何时使用互斥量,何时不使用

c - 如何将一个位序列添加到另一个序列的末尾?

c - 将整数分配给指针的 mxArray

c - C 中的二叉树

c - 不属于的随机字节,SSL_read

c - 为什么此示例代码在 Linux 上没有发出信号?

c - 如何按包含日期的字符串对数据结构进行排序?

c - 它如何使输出 "fffffffe"?

c++ - 当我用 C 编写 C++ 代码时是否可能显示错误?