替换为字母位置

发布于 2025-01-22 21:23:13 字数 995 浏览 1 评论 0原文

编写一个赋予字符串的函数,将每个字母替换为字母中的位置。如果文本中的任何内容不是字母,请忽略它,不要退还它。 a是1,b为2等。例如: 字母表(“日落设置为十二O'时钟。”) 应返回“ 20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 1 15 3 12 15 3 11”作为弦。

std::string alphabet_position(std::string message)
{ 
    message.erase(std::remove_if(message.begin(), message.end(), isspace), message.end());

    std::ostringstream os;
    for (auto const & c : message)
    {
        char c_lower = std::tolower(c);
        if (c_lower < 'a' || c_lower > 'z')  continue;
        int pos = c_lower - 'a' + 1 ;
        os << pos;
        os << ' ';
    }


    return os.str();
}


int main(){ 

  std::string text; 
  std::cout<<"Enter a phrase :"<<std::endl; 
  std::cin>>text; 
  std::string s_out = alphabet_position(text);
  std::cout<<"the alphabet positions :"<<s_out<<std::endl;


    return 0;
}

我真的在为这个挑战而苦苦挣扎。这里的问题是,当我输入短语时,代码将仅在第一个空间之前给我字母的字母位置。 例子: 输入:日落设置为十二O'时钟。 输出:20 8 5

Write a function that is given a string, replace every letter with its position in the alphabet. If anything in the text isn't a letter, ignore it and don't return it. a being 1, b being 2, etc.As an example:
AlphabetPosition("The sunset sets at twelve o' clock.")
Should return "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11" as a string.

std::string alphabet_position(std::string message)
{ 
    message.erase(std::remove_if(message.begin(), message.end(), isspace), message.end());

    std::ostringstream os;
    for (auto const & c : message)
    {
        char c_lower = std::tolower(c);
        if (c_lower < 'a' || c_lower > 'z')  continue;
        int pos = c_lower - 'a' + 1 ;
        os << pos;
        os << ' ';
    }


    return os.str();
}


int main(){ 

  std::string text; 
  std::cout<<"Enter a phrase :"<<std::endl; 
  std::cin>>text; 
  std::string s_out = alphabet_position(text);
  std::cout<<"the alphabet positions :"<<s_out<<std::endl;


    return 0;
}

I am really struggling with this challenge. The Issue here is that when I enter a phrase, the code will give me only the alphabet positions of the letters before the first space.
example:
Input: The sunset sets at twelve o' clock.
Output: 20 8 5

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文