C语言,将s字符串中ASCII码值为偶数的字符删除,剩余的字符组成一个新字符串放在t数组中,求大神给答案!

2024年12月03日 08:42
有3个网友回答
网友(1):

#include 
#define LENGTH 100
int main()
{
    char s[LENGTH] = "abcdefghijklmn1234567890 hello world!";
    char t[LENGTH] = {0};
    int i = 0, j = 0;
                                                                                                                                                            
    for (; s[i] != '\0'; i++)
        if (s[i] % 2 != 0) t[j++] = s[i];
                                                                                                                                                            
    printf("s = %s\nt = %s", s, t);
                                                                                                                                                            
    // 运行结果应为
    // s = abcdefghijklmn1234567890 hello world!
    // t = acegikm13579eowo!
                                                                                                                                                            
    return 0;
}

写个简单的限制长度的字符串删除,严格的说这个需求应该用动态分配内存的方式,根据字符串的实际长度进行内存分配

网友(2):

你可以直接赋值t数组,信息从s来,只是指针一下跳俩字符就行了,
循环的条件是剩余的字符数大于1
赋值
指针调整

网友(3):

#include
void func(char *s, char*t)
{
char *p;
for (p=t; *s; s++)
if (*s % 2 != 0)
*p++ = *s;
*p = '\0';
}
int main()
{
char str[] = "abcdefgh";
char t[100];
func(str, t);
printf("t = %s\n", t);
return 0;
}