1

首先,我正在尝试创建一个程序,该程序采用两个字符数组并从第一个数组中删除第二个数组中出现的任何字符。我添加了评论,以便更容易理解正在发生的事情。

   #include <stdio.h>

void rcfs(char s[], char t[]){
    int i=0, j=0;
    while (t[i] != '\0')
        ++i; /*find size of t*/
    for (int x=0;x<i;++x){ /*go through both vals of x and
    check vals of s to see if they equal a val of x, if so set j of s to 0*/
        while (s[j]!=0){
            if (s[j]==t[x]){
                s[j]=0;
            }
            j++;
        }
        if (x<i-1)
            j=0;
    }
    char new[8]; /*new char arr to be assigned to s*/
    int x=0; //seperate counter that increments only when chars are added to new
    for (int q=0;q<j;q++){
        if (s[q]!=0)
            new[x++]=s[q];
    }
    new[7]=0;
    s=new; //maybe these need be pointers
}

int main(){
    char s[]="I eat food";
    char t[]="oe";
    printf("Pre: %s\n", s);
    rcfs(s, t);
    printf("Post: %s", s);
    return 0;
}

这是输出: 图像 而不是 'Post: I' 它应该是: 'Post: I at fd' 总而言之,我得到了错误的输出,我目前不知道如何修复它。

4

3 回答 3

3

我建议您将算法翻转并s在外循环中循环。我还建议您使用strlen来查找字符串的长度并strchr找出字符串中是否存在字符。

例子:

#include <string.h>

void rcfs(char *s, char t[]) {   
    char *sw = s; // current writing position

    for(; *s != '\0'; ++s)  {        // s is the current reading pos
        if(strchr(t, *s) == NULL) {  // *s is not in t
            *sw = *s;                // save this character at sw
            ++sw;                    // and step sw
        }        
    }

    *sw = '\0'; // null terminate
}

演示

于 2022-01-25T08:45:14.453 回答
3

你的方法是完全错误和错误的。

例如这个while循环

    while (s[j]!=0){
        if (s[j]==t[x]){
            s[j]=0;
        }
        j++;
    }

如果您已经在字符串 s 中将某个前面的字符设置为 0,则可能无法找到等于字符 t[x] 的字符。

例如 ifs = "12"t = "12"then 在 for 循环的第一次迭代之后

for (int x=0;x<i;++x){

数组 s 看起来像 s ="\02"所以 for 循环的第二次迭代中的 while 循环将由于条件而立即退出

while (s[j]!=0){

这个带有幻数的字符数组的声明8

char new[8];

没有意义。用户可以向函数传递任意长度的字符串。

在这个赋值语句中

s=new

s指针类型的局部变量char *(由于编译器将具有数组类型的参数调整为指向数组元素类型的指针)由局部数组new的第一个元素的地址分配。这不会改变 main 中声明的源数组。

在不使用标准 C 字符串函数的情况下,您的函数可以通过以下方式声明和定义,如下面的演示程序所示。

#include <stdio.h>

char *rcfs( char s1[], const char s2[] )
{
    if (*s2)
    {
        char *src = s1, *dsn = s1;
        do
        {
            size_t i = 0;
            while (s2[i] != '\0' && s2[i] != *src) ++i;
            if (s2[i] == '\0')
            {
                if (src != dsn) *dsn = *src;
                ++dsn;
            }
        } while (*src++);
    }

    return s1;
}

int main( void )
{
    char s[] = "I eat food";

    printf( "Pre: %s\n", s );

    printf( "Post: %s\n", rcfs(s, "oe"));
}

程序输出为

Pre: I eat food
Post: I at fd
于 2022-01-25T08:58:20.610 回答
1

首先:

char new[8]在 function 之外实例化rcfs,将其传递给该函数,并在函数返回后打印它:

char new[8];
rcfs(s, t, new);
printf("Post: %s", new);

当然应该声明该函数void rcfs(char s[], char t[], char new[])

于 2022-01-25T08:25:26.693 回答