【发布时间】:2017-10-06 08:10:48
【问题描述】:
嗨,我有两个不同的字符串,我需要在字符串中找到共同的字符。我设法获得了公共字符串,但我需要为不具有相同字符的输入返回“空字符串”。
当前问题:
输入1:abc
输入2:定义
output: ' // 它应该是“空字符串”;
这是我的代码:
#include <stdio.h>
#include <string.h>
void strInterset(char * str1, char * str2, char * str3);
int main() {
char str1[50], str2[50], str3[50];
printf("Enter str1: \n");
scanf("%s", str1);
printf("Enter str2: \n");
scanf("%s", str2);
strInterset(str1, str2, str3);
if (*str3 == '\0')
printf("strIntersect(): null string\n");
else
printf("strIntersect(): %s\n", str3);
return 0;
}
void strInterset(char * str1, char * str2, char * str3) {
int i = 0, j;
for (i; *(str1 + i) != '\0'; i++) {
for (j = 0; *(str2 + j) != '\0'; j++) {
if ( *(str2 + j) == *(str1 + i)) {
strcpy(str3, str1 + i);
str3++;
}
}
}
}
【问题讨论】:
-
上述代码遇到了什么问题?将 str3[50] 初始化为 null
-
如果没有公共字符,
str3是一个未初始化的变量,具有不确定的值。 -
即使有普通字符,
str3也不会被NUL终止 -
@ChrisTurner
strcpy复制 nul 终止符。 -
对不起,我的意思是输出应该是“空字符串”