【问题标题】:Trying to temporarily convert entire string to lowercase and remove spaces尝试将整个字符串临时转换为小写并删除空格
【发布时间】:2018-05-01 21:06:02
【问题描述】:

所以我的程序是一个仅使用字符串库和 C++ sting 对象的回文检查器函数。为了检查用户输入的字符串是否是回文,我需要将整个字符串转换为小写并删除空格以检查字符串及其反转是否相等。我试过查找解决方案,但我只找到了使用不同库和创建新函数的答案。这是我目前的代码。

#include <iostream>
#include <string>

using namespace std;

string checkPalin();

int main()
{
    string result = checkPalin();

    cout << "The palindromes are: " << result;
}

string checkPalin()
{
    int stringNum, time = 0;
    string list;
    string str1;
    string reverse;
    cout << "How many strings? " << endl;
    cin >> stringNum;
    cout << "Enter the strings: " << endl;

    do
    {
        getline(cin, str1);


        int size = str1.length();
        for (int i = size - 1; i >= 0; i--)
            reverse += str1[i];

        if ((str1.compare(reverse)) == 0)
        {
            list += str1;
        }

        time++;
    } while (time <= stringNum);

    return list;
}

【问题讨论】:

  • 检查This。还有std::reverse,所以你不必写它。我认为你可以使用所有你想要的std
  • “我只找到了答案……创建新功能”是什么意思?你不打算写函数吗?
  • 这是一个家庭作业问题,还是来自一些愚蠢的在线测验网站的问题,没有人真正关心?
  • PhotometricStereo 我应该只用一个函数和main
  • 这是家庭作业

标签: c++ string object palindrome lowercase


【解决方案1】:

这样的事情怎么样

std::string inputString = "WhatEver", cleanString;
for (char & c : inputString)
    if (c != ' ')
        cleanString += std::tolower(static_cast<unsigned char>(c));

如果 char 值不能表示为 unsigned char,则 std::tolower 未定义,因此强制转换。

【讨论】:

    猜你喜欢
    • 2014-12-13
    • 2023-01-12
    • 2015-11-16
    • 1970-01-01
    • 2022-06-10
    • 2022-01-19
    • 2016-06-03
    • 1970-01-01
    • 2011-05-01
    相关资源
    最近更新 更多