【问题标题】:How to convert alpha numerical and special characters string to alphabetical string? [closed]如何将字母数字和特殊字符串转换为字母字符串? [关闭]
【发布时间】:2019-12-01 12:21:44
【问题描述】:

在函数中,传递一个包含字母、数字和特殊字符的字符串。该函数应该只返回字符串中的字母。

我尝试了以下代码,但它也给出了数字。我哪里错了?

在这段代码中(使用c++11)std::string::find_first_not_of正在使用stl算法

 std::string jobName1 = "job_2";

 std::size_t found = 
  jobName1.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJK
  LMNOPQRSTUVWXYZ");
 while (found!=std::string::npos)
 {
    jobName1.erase(found,1);
    found=jobName1.find_first_not_of("abcdefghijklmnopqrstuvwxyzAB
    CDEFGHIJKLMNOPQRSTUVWXYZ",(found+1));
 }

输入:

job_2

输出:

job2

预期:

job

【问题讨论】:

  • 投票结束是一个错字。你有一个错误。 find_first_not_of("abcdefghijklmnopqrstuvwxyzAB CDEFGHIJKLMNOPQRSTUVWXYZ",(found+1)) 应该是 find_first_not_of("abcdefghijklmnopqrstuvwxyzAB CDEFGHIJKLMNOPQRSTUVWXYZ",(found)) 因为你删除了 found 所以 found + 1 是下一个字符,因为 found 现在是下一个字符。
  • @NathanOliver 太好了...感谢您的快速回复。
  • @Sagar 下次使用std::remove_if。

标签: c++ algorithm c++11 stdstring c++-standard-library


【解决方案1】:

根据您的描述,这应该可以完成工作:

#include <iostream>
#include <string>
#include <regex>

int main ()
{
  std::string jobName1 = "job_2";
  std::regex regex ("[0-9_]*");

  auto result = std::regex_replace (jobName1, regex, "");
  std::cout << result << std::endl;

  return 0;
}

【讨论】:

    【解决方案2】:

    如果您要查找的不是您编写的代码,您可以使用std::remove_if:

     #include <iostream>
     #include <string>
     #include <algorithm>
     #include <cctype>
    
     int main()
     {
         std::string jobName1 = "job_2";
         jobName1.erase(std::remove_if(jobName1.begin(), jobName1.end(),
                                      [](char ch){return !std::isalpha(ch);}),
                                      jobName1.end());
         std::cout << jobName1;
     }
    

    输出:

    job
    

    【讨论】:

    • 从现有字符串中为其中的所有字符创建一个新字符串不是很有效std::isalpha?类似:wandbox.org/permlink/Ve1si4N4jlMNjSkc
    • @JeJo -- 好吧,我建议您使用std::copy_if 发布答案,这基本上就是您的代码正在做的事情。如果你这样做,我会给予信任:-)
    【解决方案3】:

    作为已经给定的std::string::find_first_not_of、std::regex_replace、std::remove_if 解决方案的替代方案,std::copy_if 可用于将给定字符串的字符复制到新字符串,如果它是std::isalpha。(感谢 @PaulMcKenzie 提出了正确的算法)

    (See Live)

    #include <iostream>
    #include <string>
    #include <algorithm> // std::copy_if
    #include <iterator>  // std::back_inserter 
    #include <cctype>    // std::isalpha
    
    int main()
    {
        const std::string jobName1{ "job_2" };
        std::string result;
        std::copy_if(std::cbegin(jobName1), std::cend(jobName1),
            std::back_inserter(result),
            [](const char chr) noexcept { return std::isalpha(chr); });
        std::cout << result;
        return 0;
    }
    

    输出:

    job
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多