如何从字符串中删除给定字符中所有出现的C 2 [英] How to remove all occurrences of a given character from string in C?

查看:201
本文介绍了如何从字符串中删除给定字符中所有出现的C 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从一个字符串C.删除一个角色,我与我的code遇到的问题是,它消除字符串中的字符的第一个实例,但在此字符后也将清除所有内容串了。例如,去除'你好'打印'他''L'而不是'HEO

I'm attempting to remove a character from a string in C. The problem I am having with my code is that it removes the first instance of the character from the string but also wipes everything after that character in the string too. For example, removing 'l' from 'hello' prints 'he' rather than 'heo'

int i;
char str1[30] = "Hello", *ptr1, c = 'l';
ptr1 = str1;
for (i=0; i<strlen(str1); i++)
{
    if (*ptr1 == c) *ptr1 = 0;
    printf("%c\n", *ptr1);
    ptr1++;
}

我需要使用指针,这和想保持尽可能简单,因为我在C.初学者
谢谢

I need to use pointers for this and would like to keep it as simple as possible since I'm a beginner in C. Thanks

推荐答案

您可以做到这一点是这样的:

You can do it like this:

void remove_all_chars(char* str, char c) {
    char *pr = str, *pw = str;
    while (*pr) {
        *pw = *pr++;
        pw += (*pw != c);
    }
    *pw = '\0';
}

int main() {
    char str[] = "llHello, world!ll";
    remove_all_chars(str, 'l');
    printf("'%s'\n", str);
    return 0;
}

这样做是为了保持一个单独的读写指针(新闻阅读和 PW 写作)总是提前读出指针,推进,只有当它不是指向给定字符写入指针。

The idea is to keep a separate read and write pointers (pr for reading and pw for writing), always advance the reading pointer, and advance the writing pointer only when it's not pointing to a given character.

这篇关于如何从字符串中删除给定字符中所有出现的C 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆