c - 交换两个字符

标签 c char

我想知道我的代码出了什么问题。 它应该交换用户指定的两个单词, 但它什么也没做。一点帮助就好了。

#include <stdio.h>

void changeW(char *ptab1, char *ptab2){
char tmp;
tmp = *ptab1;
*ptab1 = *ptab2;
*ptab2 = tmp;
printf("%s %s",ptab1,ptab2);
return;
}
int main(void) {

char tab1[25];
char tab2[25];

printf("type two words");
scanf("%s %s",tab1,tab2);
changeW(tab1,tab2);
return 0;
}

已更正代码,但问题仍然存在!我可以交换小单词,但是当它们变长时,我会在终端中看到奇怪的字符,例如 ����。

void changeW(char *ptab1, char *ptab2){
int l;
if(length(ptab1)<length(ptab2)){
l = length(ptab2);
}
else {l=length(ptab1);}
for(int i=0; i<l;i++){
char tmp;
tmp =ptab1[i];
ptab1[i] =ptab2[i];
ptab2[i]=tmp;
}
printf("%s %s",ptab1,ptab2);
return;
}
int main(void) {

char tab1[25];
char tab2[25];

printf("type two words");
scanf("%s %s",tab1,tab2);
changeW(tab1,tab2);
return 0;
}

好的,我找到了解决方案,感谢大家的帮助。 你所要做的就是改变W,

printf("%s\t%s",ptab1,ptab2);

单个空格似乎不足以分隔两个单词,制表符就可以了。

最后编辑: 事实上,搜索最长的表是没有用的,因为 tab1 和 tab2 都是 25 个字符长。

for(int i=0; i<25;i++)

工作正常。

最佳答案

您只是交换前两个字符。要交换字符串,您必须使用循环。

#include <stdlib.h>
#include <string.h>

void changeW(char *p1, char *p2, size_t p1_len)
{
    char *tmp = malloc (p1_len); /* or [C99] char tmp[p1_len]; */
    strcpy (tmp, p1);
    strcpy (p1, p2);
    strcpy (p2, tmp);
}

另一种可能性是交换指针。

#include <stdio.h>
#include <stdlib.h>

void swap_strings(char **p1, char **p2)
{
    char *tmp = *p1;
    *p1 = *p2;
    *p2 = tmp;
}

int main (void)
{
    char s1[] = "hello";
    char s2[] = "word";

    char *p1 = s1;
    char *p2 = s2;

    puts(p1);
    puts(p2);

    swap_strings(&p1, &p2);

    puts(p1);
    puts(p2);

    return 0;
}

关于c - 交换两个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13900448/

相关文章:

c++ - 我是否从 "const char *"正确转换为 "TCHAR*"?

c - ANSI C 不允许在固定时间段后在同一位置打印每个字符吗?

c - 没有变量的 C 函数调用是否在运行时预编译或评估?

c++ - C/C++ NaN 常量(字面量)?

c - 在C中添加和打印多个字符

c - while 循环,从 scanf 读取 int 与 char,true 和 false

c++ - 为什么我的字符串在减去字符时会附加空值?

c - 如何使用 CodeBlocks 解决此 C 代码中的构建和运行错误?

c - fwrite 写一个整数

c++ - 将无符号字符数组转换为整数