如何检查字符串是否包含空格/制表符/新行(任何空白)? [英] How to check if a string contains spaces/tabs/new lines (anything that's blank)?

查看:1018
本文介绍了如何检查字符串是否包含空格/制表符/新行(任何空白)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有一个isspace函数检查空格,但是这将需要我遍历字符串中的每个字符,这可能是坏的性能,因为这将被称为很多。是否有快速的方法来检查std :: string是否只包含空格?

I know there's an "isspace" function that checks for spaces, but that would require me to iterate through every character in the string, which can be bad on performance since this would be called a lot. Is there a fast way to check if a std::string contains only spaces?

例如:

function("       ") // returns true
function("    4  ") // returns false

我想到的一个解决方案是使用regex,然后我会知道它只包含空格如果它是假的...但我不知道如果这将更有效率

One solution I've thought of is to use regex, then i'll know that it only contains whitespace if it's false... but i'm not sure if this would be more efficient than the isspace function.

regex: [\w\W] //checks for any word character(a,b,c..) and non-word character([,],..)

推荐答案

任何方法都需要查看字符串的每个字符。在每个字符上调用 isspace()的循环效率很高。如果 isspace()被编译器内联,那么这将是darn接近最优。

Any method would, of necessity, need to look at each character of the string. A loop that calls isspace() on each character is pretty efficient. If isspace() is inlined by the compiler, then this would be darn near optimal.

当然,只要看到一个非空格字符就中止。

The loop should, of course, abort as soon as a non-space character is seen.

这篇关于如何检查字符串是否包含空格/制表符/新行(任何空白)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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