C++ 字符串中小写字母转换成大写字母

时间:2025-04-23 08:47:11
题目描述

编写函数int f (char s[ ]),将字符串中所有的小写字母转换成对应的大写字母,其他字符不变,并统计被转换字母的个数,将其作为函数值返回。要求主函数中输入该字符串,最后输出转换后的新字符串,和转换字母的个数。

输入描述

输入一个字符串。

输出描述

两行,第一行输出转换后的新字符串,第二行输出被转换的小写字母个数。

输入样例
ser34GHj
输出样例
SER34GHJ
4
#include <iostream>
#include <cctype>

using namespace std;

int f(char s[]){
	int i;
	int count = 0; 
	
	for(i = 0;s[i] != '\0'; i++){
        if(s[i] >= 'a' && s[i] <= 'z') { // 只获取a~z的ASCII码
        	s[i] -= 32; // 由于每个字母对应着ASCII码,所以只需要修改对应的ASCII码,就能实现小写转换大写
        	count++;
		}
    }   
    
	return count;
}



int main(void){
	char str[128];
	int num;
	
	cin >> str;
	
	num = f(str);
	
	cout << str << endl;
	cout << num << endl;
}