转换大写字母为小写,反之亦然一个字符串

问题描述 投票:2回答:3

我想一个字符串中的字符转换从大写改为小写。没有编译错误,但我仍然得到相同的输出输入:

#include <iostream>
#include<string.h>
#include<ctype.h>
using namespace std;
int main() {
    char a[100];
    cin>>a;
    for(int i =0;a[i];i++){
        if(islower(a[i])){
            toupper(a[i]);
        }
        else if(isupper(a[i])){
            tolower(a[i]);
        }
    }
    cout<<a;
    return 0;
}
c++ string
3个回答
7
投票

std::toupperstd::tolower职能不到位的工作。他们返回的结果,所以你必须指定其再次a[i]

char a[100];
std::cin>>a;
for(std::size_t i =0;a[i];i++){
    if(std::islower(a[i])){
        a[i]=std::toupper(a[i]);// Here!
    }
    else if(std::isupper(a[i])){
        a[i]=std::tolower(a[i]);// Here!
    }
}
std::cout<<a;

1
投票

你可以使用标准库与返回给定字符的大写或小写字母lambda函数变换功能。

#include <algorithm>
#include <iostream>

using namespace std;


int main
{
    string hello = "Hello World!";
    transform(hello.begin(), hello.end(), hello.begin(), [](char c){
            return toupper(c);})

    cout << hello << endl;
}

这将输出HELLO WORLD!你能想象这样的小写同样的事情


0
投票

这里有一个解决方案,我发现通过调用另一个字符变量“charConvert”并设置它等于转换的字符。

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

int main() {
    char a[100];
    cin >> a;
    char charConvert;

   for (int i = 0; a[i] ; i++) {

        if  (isupper(a[i])) { 
            charConvert = tolower(a[i]);
        }
        else if (islower(a[i])) {
            charConvert = toupper(a[i]);
        }
    }
    cout << charConvert << endl;

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.