【问题标题】:How to convert lowercase characters of a string to uppercase characters in C++?如何在 C++ 中将字符串的小写字符转换为大写字符?
【发布时间】:2017-06-03 16:03:08
【问题描述】:

我有一个问题,字符串的所有小写字符都应转换为大写字符。但根据问题,不应更改代码中的某些行。我已经写了下面的代码。

 #include <iostream>
 #include <string>
 #include <stdio.h>
 #include <ctype.h>
 using namespace std;

 class StringOps {
 public:
   void stringToUpper(string &s) //This line should not be changed
  {
    char c;
    int i=0;
    while (s[i])
    {
     c=s[i];
     putchar (toupper(c));
     i++;
    }
  }
 };

 int main(void)
 {
   string str ="Hello World";  
   StringOps obj;
   obj.stringToUpper(str);
   cout << str;            //This line should not be changed
   return 0;
   }

我得到的输出为:

HELLO WORLDHello World

但是需要的输出是:

HELLO WORLD HELLO WORLD

如何制作

 cout<<str; 

main() 中的语句打印函数中计算的结果:

 void stringToUpper(string &s)

【问题讨论】:

  • 嗯,看起来您想修改stringToUpper 中的s,而不是仅仅从中读取。
  • 您应该设法使stringToUpper 更改 s 而不是像现在这样打印。
  • 谢谢!!我现在明白我的错误了。

标签: c++ string class output uppercase


【解决方案1】:

cout

这意味着您必须更改str

void stringToUpper(string &s) //这行不要改

好消息,你的方法以s为参考。

在您的代码中,您正在执行c=s[i];,您应该重新分配字符串中的字符s[i] = c

【讨论】:

    【解决方案2】:

    只针对ASCII字符的下半部分解决。

    class StringOps {
    public:
      void stringToUpper(string& s) //This line should not be changed
      {
        for (size_t i = 0; i < s.size(); ++i) {
          if (s[i] > 96 && s[i] < 123)
            s[i] -= 32;
        }
      }
    };
    

    如果您关心 ASCII 表的较高部分:

    class StringOps {
    public:
      void stringToUpper(string& s) //This line should not be changed
      {
        for (size_t i = 0; i < s.size(); ++i) {
          s[i] = toupper(s[i]);
        }
      }
    };
    

    如果你有一些多字节编码,比如 UTF-8,你将需要一些库。

    【讨论】:

    • 感谢您的努力!!
    【解决方案3】:

    您只是打印字符串并将每个字符作为大写字符,但传递给函数(通过引用)“s”的字符串不会改变。

    void stringToUpper(string &s)
    

    可以加一行让s在void stringToUpper(string &s)中得到改变

     s[i] = toupper(c);
    

    代码看起来

     c=s[i];
     s[i] = toupper(c);
     putchar (toupper(c));
     i++;
    

    输出将是

    HELLO WORLDHELLO WORLD
    

    【讨论】:

      猜你喜欢
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      • 2014-03-30
      • 1970-01-01
      • 1970-01-01
      • 2018-01-13
      • 2010-12-09
      • 1970-01-01
      相关资源
      最近更新 更多