【问题标题】:How do i check if a string has a certain number of letters and digits? [closed]如何检查字符串是否包含一定数量的字母和数字? [关闭]
【发布时间】:2017-02-26 03:46:52
【问题描述】:

我需要创建一个函数来检查我作为参数发送的字符串的前 4 个字符是否为字母,后 3 个字符是否为数字,并且它是否正好有 7 个字符。我该如何编写这个函数?

【问题讨论】:

  • 可以使用正则表达式:[A-Za-z]{4}[0-9]{3}
  • 我的课还没学过正则表达式,主要是要使用基本的东西,比如字符串库里的东西。
  • std::string::length() 检查长度是否为 7,std::count_if() 检查字符范围是否包含预期的字母和数字数量。或者使用正则表达式库。
  • 如果您真正尝试设计和编码您的功能,您将有更多机会获得帮助。
  • 我投票决定将此问题作为题外话结束,因为它要求为一个琐碎问题提供编码解决方案,除了发布问题之外没有任何其他努力的证据。

标签: c++ string function


【解决方案1】:

最简单的解决方案是遍历字符串检查每个单独的字符,例如:

#include <string>
#include <cctype>

bool is4LettersAnd3Digits(const std::string &s)
{
    if (s.length() != 7)
        return false;

    for (int i = 0; i < 4; ++i) {
        if (!std::isalpha(s[i]))
            return false;
    }

    for (int i = 4; i < 7; ++i) {
        if (!std::isdigit(s[i]))
            return false;
    }

    return true;
}

或者:

#include <string>
#include <algorithm>
#include <cctype>

bool is4LettersAnd3Digits(const std::string &s)
{
    return (
        (s.length() == 7) &&
        (std::count_if(s.begin(), s.begin()+4, std::isalpha) == 4) &&
        (std::count_if(s.begin()+4, s.end(), std::isdigit) == 3)
    );
}

或者,如果使用 C++11 或更高版本:

#include <string>
#include <algorithm>
#include <cctype>

bool is4LettersAnd3Digits(const std::string &s)
{
    if (
        (s.length() == 7) &&
        std::all_of(s.begin(), s.begin()+4, std::isalpha) &&
        std::all_of(s.begin()+4, s.end(), std::isdigit)
    );
}

【讨论】:

  • 我会将std::count_if 替换为std::all_of
  • @lisyarus std::all_of() 是 C++11 中的新功能。 std::count_if() 存在于早期版本中。不过,我已经更新了我的答案。
  • 虽然我完全理解确实存在 C++11 不可用的环境,但默认情况下假设 C++ 语言的当前官方标准(目前是 C++14)听起来合乎逻辑。如果必须使用旧版本,则应在问题中明确说明。除此之外,很好的答案!
  • @lisyarus 很多环境还没有采用 C++11,更不用说 C++14 甚至 C++17。 C++11/14 可能是当前的,但并不普及。但我确实同意问题应该相应地标记。
猜你喜欢
  • 2012-12-27
  • 1970-01-01
  • 2021-10-01
  • 1970-01-01
  • 2012-08-20
  • 1970-01-01
  • 2012-05-01
  • 2020-12-12
  • 1970-01-01
相关资源
最近更新 更多