如何操作字符串小写并存储在同一变量中

How to manipulate a string to lower case and store in same variable

本文关键字:存储 变量 何操作 操作 字符串      更新时间:2023-10-16

我有一段代码要求用户输入,它的类型是"string",这是一个非常简单的过程,我希望用户输入的任何内容都可以使用tolower()函数进行转换。它完全像它应该做的那样,但我似乎不能把它赋值给同一个变量。请帮忙好吗?

#include <locale>
#include <string>
#include <iostream>
//maybe some other headers, but headers aren't the problem, so I am not going to list them all
while (nCommand == 0)
        {  
            locale loc;
            string sCommand;
            cin >> sCommand;
            for (int i = 0; i < sCommand.length(); ++i)
            {
            sCommand = tolower(sCommand[i],loc);
            cout << sCommand;
            }

例如,如果用户在帮助命令中输入h

我希望它看起来是这样的如果用户输入HELP或者HELP或者HELP

当你真正想做的是将存储在该位置的字符赋值为小写版本时,你正在将字符串赋值给一个字符。

所以改成

sCommand = tolower(sCommand[i], loc);

:

sCommand[i] = tolower(sCommand[i], loc);
//      ^^^

这是Boost字符串算法将整个问题简化为单个表达式的另一种情况:

boost::algorithm::to_lower(sCommand)

尝试Boost库。从长远来看,它会对你有很大的帮助,让你专注于真正的问题,而不是像第一百万个程序员那样写自己的"将字符串转换为小写字母"的函数。