返回完整的大小写转换字符串

Return the complete uppercase/lowercase converted string

本文关键字:转换 字符串 大小写 返回      更新时间:2024-09-28

我正在编写一个程序,将字符串中的所有小写字母转换为大写字母,反之亦然。但是,我发现我的程序无法返回整个转换后的字符串。

以下是结果和我的程序代码
输入:"调查";,输出:";A">
输入:"你好";,输出:";hELLO";。

#include <iostream>
#include <cstring>
using namespace std;
int main() {
char inWord[50], outWord[50];
int j = 0;
cin.getline(inWord, 50);
for (j = 0; j < strlen(inWord); j++)
{
//upper to lower
if (inWord[j]>='A'&&inWord[j]<='Z')
outWord[j] = inWord[j] + 'a' - 'A';
//lower to upper
else
outWord[j] = inWord[j] + 'A' - 'a';
}
cout << outWord;
return 0;
}

您需要考虑非字母字符。现在您正在将空格转换为0,这是cout知道他需要停止读取字符串的方式。这是一个简单的解决方案:

#include <iostream>
#include <cstring>
using namespace std;
int main() {
char inWord[50], outWord[50];
cin.getline(inWord, 50);
for (int j = 0; j < strlen(inWord); j++)
{
char c = inWord[j];
//upper to lower
if (c>='A' && c<='Z')
outWord[j] = c + 'a' - 'A';
//lower to upper
else if (c>='a' && c<='z')
outWord[j] = c + 'A' - 'a';
else
outWord[j] = c;
}
cout << outWord;
return 0;
}

如果您使用C++编程,您可能应该用std::string替换这些char[50],并避免使用名称空间std:

#include <iostream>
#include <string>
int main() {
std::string inWord, outWord;
std::getline(std::cin, inWord);
outWord.reserve(inWord.size());
for (int i = 0; i < inWord.size(); i++)
{
char c = inWord[i];
//upper to lower
if (c>='A' && c<='Z') {
outWord.push_back(c + 'a' - 'A');
}
//lower to upper
else if (c>='a' && c<='z') {
outWord.push_back(c + 'A' - 'a');
}
else {
outWord.push_back(c);
}
}
std::cout << outWord;
return 0;
}

在ascii中,

' '不在'A'-'Z'范围内,因此采取第二个分支。根据危险性,其值为'a' - 'A'。产生CCD_ 5(C串的nul终止子(。

要解决这个问题,您必须处理第三种情况:

const std::size_t size = strlen(inWord)
for (std::size_t j = 0; j < size; j++)
{
//upper to lower
if (inWord[j]>='A'&&inWord[j]<='Z')
outWord[j] = inWord[j] + 'a' - 'A';
//lower to upper
else if (inWord[j]>='a'&&inWord[j]<='z')
outWord[j] = inWord[j] + 'A' - 'a';
else
outWord[j] = inWord[j];
}

'a'-'z''A'-'Z'不能保证是连续的范围(它适用于Ascii,而不是EBCDIC(,因此您可以使用标准方法(即使它们的接口容易出错:((:

const std::size_t size = strlen(inWord)
for (std::size_t j = 0; j < size; j++)
{
unsigned char c = static_cast<unsigned char>(inWord[j]);
if (std::isupper(c))
outWord[j] = static_cast<char>(std::tolower(c));
//lower to upper
else if (std::islower(c))
outWord[j] = static_cast<char>(std::toupper(c));
else
outWord[j] = inWord[j];
}

如果您想将所有字母(例如(转换为相反的大小写,则需要检查字符串在输入后的大小写。(例如,通过计算大写字符(
现在您正在反转每个字母的大小写,就像您对循环中的每个字母进行if-else比较一样。如果只执行两个分支条件中的一个,它将转换为相同的情况

关于如何改进你的风格的几句话:

  • 如果不在循环外使用int,则可以在for循环内定义j for (int j = 0; j < strlen(inWord); j++){}
  • "a"-"a"answers"a"-"a">
    具有相同的绝对值,并且在循环过程中不会发生变化,因此您可以在循环之前定义一个变量,然后在循环内部分别进行加法或减法运算

在ascii的情况下,C++将字符视为8位数字也是很有用的,这就是偏移量计算有效的原因:链接到ASCII表