用C模仿Python的带()函数 [英] Mimic Python's strip() function in C

查看:111
本文介绍了用C模仿Python的带()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用C开始在一个小玩具项目和最近已经抓我的头在模仿条()功能,是Python字符串对象的一部分的最佳方式。

I started on a little toy project in C lately and have been scratching my head over the best way to mimic the strip() functionality that is part of the python string objects.

阅读周围的fscanf或sscanf的说,该字符串高达遇到的第一个空格处理。

Reading around for fscanf or sscanf says that the string is processed upto the first whitespace that is encountered.

与fgets不利于无论是作为我还是坚持换行符左右。
我也尝试和strchr()来搜索空白和返回的指针设置为'\\ 0'明确,但似乎并没有工作。

fgets doesn't help either as I still have newlines sticking around. I did try a strchr() to search for a whitespace and setting the returned pointer to '\0' explicitly but that doesn't seem to work.

推荐答案

有是条没有标准的C实现()或修剪()函数。这就是说,这里是包含在Linux内核中的一项:

There is no standard C implementation for a strip() or trim() function. That said, here's the one included in the Linux kernel:

char *strstrip(char *s)
{
        size_t size;
        char *end;

        size = strlen(s);

        if (!size)
                return s;

        end = s + size - 1;
        while (end >= s && isspace(*end))
                end--;
        *(end + 1) = '\0';

        while (*s && isspace(*s))
                s++;

        return s;
}

这篇关于用C模仿Python的带()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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