简体   繁体   English

使用C编程将两个单词交换为字符串

[英]Swap two words in a string using C programming

I am close to finish writing a program to swap two words inputed to a program. 我即将完成编写程序以交换输入到程序中的两个单词。 If i input "Billy Bob" the output will be "@\\300_\\377" Something weird like that... I believe there is something wrong with my scanf but not quite sure. 如果我输入“ Billy Bob”,输出将是“ @ \\ 300_ \\ 377”,有点奇怪……我相信我的scanf出了点问题,但不太确定。 Here is what i have so far.. 这是我到目前为止所拥有的..

{ int i,j,l;
char str[59];
printf("Enter the string\n");
scanf("%s", &str[59]);
l=strlen(str);
for(i=l-1; i>=0; i--)
{ if(str[i]==' ')
{ for(j=i+1; j<l; j++)
    printf("%c",str[j]);
    printf(" ");
    l=i;
    }
    if(i==0) 
    { printf(" "); 
        for(j=0; j<l; j++) 
            printf("%c",str[j]); 
    } 
} 
scanf("%s", &str[59]);

Writes the input at the end of the allocated space. 将输入写入分配的空间的末尾。 Use the address of the first element: 使用第一个元素的地址:

scanf("%s", str);

but this will give you the first word, so either do: 但这会给您第一个字,因此可以执行以下操作:

scanf("%s %s", str1, str2); // str1, str2 are arrays

or use fgets: 或使用fgets:

fgets(str, 59, stdin);

Instead of using scanf("%s", &str[59]); 而不是使用scanf("%s", &str[59]); , you could use gets(str); ,您可以使用gets(str); .

It works perfectly fine... 它工作得很好...

This is wrong: 这是错误的:

 scanf("%s", &str[59]);  
 //^not reading the str, str[59] is even out of bound

should be: 应该:

scanf("%s", str);

That way of writing the function is somewhat difficult to read. 这种编写函数的方式有些难以理解。 I'm not exactly sure what circumstances you are writing it in but an alternative solution would be to split up the input string by a token, in this case a space, and print out the two strings in the opposite order. 我不确定您在什么情况下编写它,但是另一种解决方案是用标记(在此情况下为空格)分割输入字符串,并以相反的顺序打印出两个字符串。 An example of the function strtok() can be found here . 函数strtok()的示例可以在此处找到。

Something like this: 像这样:

char str[] ="billy bob";
char * firstToken;
char * secondToken
firstToken = strtok(str, " ");
secondToken = strtok(NULL, " ");
printf("%s %s", secondToken, firstToken);

You're passing the first address after str to scanf. 您正在将str之后的第一个地址传递给scanf。 Change &str[59] to str . &str[59]更改为str

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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