我试图编写一个函数,该函数删除字符串s1
中的每个字符,该字符与字符串s2
中的任何字符匹配。这是挤压方法的测试代码。
#include <stdio.h>
void squeeze(char s1[], char s2[]);
int main()
{
char s1[20] = "HelloWorld", s2[20] = "ol";
squeeze(s1, s2);
printf("%sn", s1);
return 0;
}
void squeeze(char s1[], char s2[])
{
int i, j, k;
k = 0;
for (i = 0; s1[i] != ' '; ++i) {
for (j = 0; s2[j] != ' '; ++j) {
if (s1[i] != s2[j])
s1[k++] = s1[i];
}
}
s1[k] = ' ';
}
当我运行此代码时,终端总是给出Segmentation fault: 11
.谁能给我任何提示为什么会发生这种情况?
示例:
#include <stdio.h>
static int found(char *str, char c) { // return 1 if c is found in str
for (size_t i = 0; str[i] != ' '; i++) {
if (str[i] == c) {
return 1;
}
}
return 0;
}
static void squeeze(char *a, char *b) {
size_t k = 0;
for (size_t i = 0; a[i] != ' '; i++) { // use size_t to iterate on a c-string
if (found(b, a[i]) != 1) {
a[k++] = a[i]; // copy only if a[i] is not in b
}
}
a[k] = ' ';
}
int main(void) {
char a[] = "HelloWorld"; // you should let auto size
char b[] = "ol"; // and separate declaration
squeeze(a, b);
printf("%sn", a);
}
你的代码问题s1[k++] = s1[i];
尝试使用新阵列
请参阅以下代码
#include<stdio.h>
char *squeeze(char s1[], char s2[]);
int main()
{
char s1[20] = "HelloWorld", s2[20] = "olH";
squeeze(s1, s2);
return 0;
}
char *squeeze(char s1[], char s2[])
{
int i, j, k;
k = 0;
char arr[100]; // new array
int flag = 0;
for (i = 0; s1[i] != ' '; i++) {
flag = 0;
for (j = 0; s2[j] != ' '; ++j) {
if (s1[i] == s2[j])
{
flag = 1;
break;
}
}
if (flag == 0)
{
arr[k++] = s1[i];
}
}
arr[k] = ' ';
printf("%s",arr);
}