【问题标题】:c++ char comparison to see if a string is fits our needsc++ char比较看一个字符串是否符合我们的需要
【发布时间】:2013-04-25 09:42:11
【问题描述】:

如果字符串变量tablolar 的字符不包含任何字符,但a-z',' 之间的小写字母,我想做我的工作。你有什么建议?

如果字符串tablolar是;

"tablo"->没关系

"tablo,tablobir,tabloiki,tablouc"->没关系

"ta"->没关系

如果是的话;

“tablo2”->不行

"ta546465"->不行

“Tablo”->不行

"tablo,234,tablobir"->不行

"tablo^%&!)=(,tablouc"-> 不行

我尝试的是 wrog;

    for(int z=0;z<tablolar.size();z++){
    if ((tablolar[z] == ',') || (tablolar[z] >= 'a' && tablolar[z] <= 'z'))
{//do your work here}}

【问题讨论】:

  • 代码中的错误是您确实为字符串中的每个有效字符工作。相反,您应该首先检查所有字符,然后仅在它们都有效时才起作用。
  • 您的方法的问题在于,对于每个匹配的字符,它“[did] your work”一次,而不是记录整个字符串是否匹配,然后决定是否执行工作(一次) ....您可以根据 Detheroc 的回答将其移动到函数中,或者在发现非法字符时将布尔值设置为 false。

标签: c++ string comparison char


【解决方案1】:

tablolar.find_first_not_of("abcdefghijknmopqrstuvwxyz,") 将返回第一个无效字符的位置,如果字符串正常,则返回std::string::npos

【讨论】:

  • 这是解决问题的好钥匙。我是否可以建议扩展一些关于他应该如何使用它的更多解释?
  • @hmz: bool good = tablolar.find_first_not_of("abcdefghijknmopqrstuvwxyz,") == std::string::npos
【解决方案2】:
bool fitsOurNeeds(const std::string &tablolar) {
    for (int z=0; z < tablolar.size(); z++)
        if (!((tablolar[z] == ',') || (tablolar[z] >= 'a' && tablolar[z] <= 'z')))
            return false;
    return true;
}

【讨论】:

  • 为什么是int?如果'a''z' 没有分配为'0''9' 的连续代码怎么办?
  • int 有什么问题?他们没有连续代码是常见的吗?
  • @Detheroc:是的,在 IBM 系统上。 (EBCDIC)。
  • @MSalters:所以问题可能是,IBM 系统通用吗? :D
  • int 可能无法接收string::size() 可以返回的所有值。然后,如果你使用警告,它可能会给你一个警告。
【解决方案3】:

c 函数 islower 测试小写。所以你可能想要一些类似的东西:

#include <algorithm>
#include <cctype> // for islower

bool fitsOurNeeds(std::string const& tabular)
{
    return std::all_of(tabular.begin(), tabular.end(),
        [](char ch)
    {
        return islower(ch) || ch == ',';
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    相关资源
    最近更新 更多