从 C 语言中的给定字符串中删除前面的空格和制表符 [英] Remove preceding spaces and tabs from a given string in C language

查看:11
本文介绍了从 C 语言中的给定字符串中删除前面的空格和制表符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么 C 函数(如果有)从字符串中删除所有前面的空格和制表符?

What C function, if any, removes all preceding spaces and tabs from a string?

推荐答案

在 C 中,字符串由指针标识,例如 char *str,也可能是数组.无论哪种方式,我们都可以声明我们自己的指向字符串开头的指针:

In C a string is identified by a pointer, such as char *str, or possibly an array. Either way, we can declare our own pointer that will point to the start of the string:

char *c = str;

然后我们可以让我们的指针越过任何类似空格的字符:

Then we can make our pointer move past any space-like characters:

while (isspace(*c))
    ++c;

这将使指针向前移动,直到它不指向空格,即在任何前导空格或制表符之后.这使原始字符串保持不变 - 我们刚刚更改了指针 c 指向的位置.

That will move the pointer forwards until it is not pointing to a space, i.e. after any leading spaces or tabs. This leaves the original string unmodified - we've just changed the location our pointer c is pointing at.

你需要这个包含来获取 isspace:

You will need this include to get isspace:

#include <ctype.h>

或者,如果您愿意自己定义什么是空白字符,您可以编写一个表达式:

Or if you are happy to define your own idea of what is a whitespace character, you can just write an expression:

while ((*c == ' ') || (*c == '	'))
    ++c;

这篇关于从 C 语言中的给定字符串中删除前面的空格和制表符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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