检查有效的方法,如果标准::字符串只有空间 [英] Efficient way to check if std::string has only spaces

查看:88
本文介绍了检查有效的方法,如果标准::字符串只有空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是跟朋友说起这将是检查是否为std :: string只有空间的最有效方式。他需要做的嵌入式项目,他正在上,显然这样的优化问题给他。

我想出了以下code,它使用的strtok()

 布尔has_only_spaces(标准::字符串&安培; STR)
{
    字符*令牌= strtok的(const_cast会<字符*>(str.c_str()),);    而(令牌!= NULL)
    {
        如果(*令牌!='')
        {
            返回true;
        }
    }
    返回false;
}

我在找这个code的反馈和更有效的方式来执行这个任务,也欢迎。


解决方案

 如果(str.find_first_not_of('')!=标准::字符串::非营利组织)
{
    //有一个非空格。
}

I was just talking with a friend about what would be the most efficient way to check if a std::string has only spaces. He needs to do this on an embedded project he is working on and apparently this kind of optimization matters to him.

I've came up with the following code, it uses strtok().

bool has_only_spaces(std::string& str)
{
    char* token = strtok(const_cast<char*>(str.c_str()), " ");

    while (token != NULL)
    {   
        if (*token != ' ')
        {   
            return true;
        }   
    }   
    return false;
}

I'm looking for feedback on this code and more efficient ways to perform this task are also welcome.

解决方案

if(str.find_first_not_of(' ') != std::string::npos)
{
    // There's a non-space.
}

这篇关于检查有效的方法,如果标准::字符串只有空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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