如何遍历字符串并将其转换为小写? [英] How do I loop through a string and convert to lowercase?

查看:68
本文介绍了如何遍历字符串并将其转换为小写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道不久前还有其他几个问题,但是我仔细检查了一下,仍然不明白.我正在尝试以字符串形式获取用户输入,然后遍历该字符串,将所有大写字母都转换为小写字母,以便可以将所有字母全部显示为小写字母.我要去哪里错了?

I know there were a couple of other questions on this from a while back, but I looked over those and still couldn't figure it out. I'm trying to take user input in the form of a string, then loop through that string converting all of the uppercase to lowercase so that I can display it all in lowercase. Where am I going wrong?

int main()
{
    cout << "Enter Text: ";
    string Text;
    getline(cin, Text);
    for(int i=0; i<Text.length(); i++)
    {
        if(islower(Text[i]) == false)
        {
            tolower(Text[i]);
            i++;
        }
        Text[i] = Text[i];
    }
    cout << "Your text is: ";
    cout << Text;
    cout << "\n";
}

我对C ++还是很陌生,如果我说即使在哪里出了错我也有很多想法,我会撒谎.第11行,其中 for 循环表示正在尝试比较两个不同的符号,但是我不知道这意味着什么,或者这是否是我的问题的根源.第15行的 tolower()表示正在忽略使用纯属性声明的函数的返回值",但我仍然不知道这是什么意思.请帮忙.

I'm very new to C++ and I'd be lying if I said I had much of an idea even where I was going wrong. Line 11, where the for loop is says that it's trying to compare two different signs, but I don't know what that means or if that's the source of my problem. Line 15 where the tolower() is says that it's 'ignoring return value of function declared with pure attribute' but I still don't know what that means either. Please help.

推荐答案

几点:

  • tolower 返回小写字符(如果存在)('A'变为'a''a'不变,'9'不变,等等)
  • Text [i] = Text [i]; 行不执行任何操作,您需要 Text [i]= tolower(Text [i]);
  • 无需检查每个字符是否为小写, tolower 会为您处理
  • tolower returns the lowercase character if it exists ('A' becomes 'a', 'a' is unchanged, '9' is unchanged, etc.)
  • The line Text[i] = Text[i]; does not do anything, you want Text[i] = tolower(Text[i]);
  • There is no need to check if each character is lowercase, tolower will handle that for you

简体:

#include <iostream>

using namespace std;

int main() {
    cout << "Enter Text: ";
    string Text; 
    getline(cin, Text);
    for (int i = 0; i < Text.length(); i++)
        Text[i] = tolower(Text[i]);
    cout << "Your text is: ";
    cout << Text;
    cout << "\n";
}

这篇关于如何遍历字符串并将其转换为小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆