我试图扭转字符串中的单词,我刚开始学习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 ;
}
出乎意料的是&#39; =&#39; 。 就像我的名字一样 是name = my
请进行必要的更正。
答案 0 :(得分: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);
}