我正在尝试反转字符串中的单词,我刚刚开始学习 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/