将一长串字符串里的小写字母转换成大写,不使用比较操作

本文介绍了一种使用C++实现将字符串转换为全大写的方法。通过位操作技巧,该算法能高效地将ASCII码表示的小写字母转换为其对应的大写字母形式。此方法特别适用于需要快速文本处理的应用场景。
#include <iostream>
using namespace std;
void ToUpper(char* aPtr);
int main(int argc ,char ** argv){
	char ptr[]="sdfsasaAAdss";

	ToUpper(ptr);
	cout<<ptr<<endl;
}

void ToUpper(char* aPtr){
	//a~z的ascii码:97~122 也就是:1100001~1111010
	//A~Z的ascii码:65~90 也就是:100 0001~1011010
	//10111111

	while(*aPtr!='\0'){
		*aPtr =(*aPtr) &223;
		++aPtr;
	}
}


由于相差刚好32,所以可以用与的操作



在C++中,有多种方法可以将字符串中的小写字母转换成大写字母,以下为几种常见实现方式: ### 方法一:使用字符数组和循环 ```cpp #include <iostream> #include <cstring> using namespace std; int f(char s[]) { int count = 0; for (int i = 0; s[i] != '\0'; i++) { if (s[i] >= 'a' && s[i] <= 'z') { s[i] -= 32; count++; } } return count; } int main() { char s[1024]; cin.getline(s, 1024); int convertedCount = f(s); cout << "转换后的字符串: " << s << endl; cout << "转换字母的个数: " << convertedCount << endl; return 0; } ``` 该方法定义了函数`f`,遍历字符数组,当字符是小写字母时,将其ASCII码值减去32转换大写字母,并统计转换字母的个数。在`main`函数中,输入字符串,调用`f`函数进行转换并输出结果[^1]。 ### 方法二:使用指针 ```cpp #include <iostream> using namespace std; void toUp(char * str) { char *p = str; while (*str != '\0') { if (*str >= 'a' && *str <= 'z') { *str -= 32; } str++; } str = p; } int main() { char s[1024]; cin.getline(s, 1024); toUp(s); cout << "转换后的字符串: " << s << endl; return 0; } ``` 此方法定义了`toUp`函数,利用指针遍历字符串,将小写字母转换大写字母。在`main`函数中,输入字符串,调用`toUp`函数并输出转换后的字符串[^2]。 ### 方法三:使用`std::string`和`getline` ```cpp #include <string> #include <iostream> using namespace std; int main() { string str; getline(cin, str); for (int i = 0; i < str.size(); i++) { if ('a' <= str[i] && str[i] <= 'z') { str[i] = str[i] - ('a' - 'A'); } cout << str[i]; } return 0; } ``` 该方法使用`std::string`类型存储字符串,通过`getline`函数输入可能包含空格的字符串。遍历字符串,将小写字母转换大写字母并输出[^3]。 ### 方法四:使用`strlen`函数 ```cpp #include<bits/stdc++.h> using namespace std; int main() { char a[1001]; cin >> a; int length = strlen(a); for (int i = 0; i < length; i++) { if (a[i] >= 'a' && a[i] <= 'z') { a[i] -= 32; } } cout << a << endl; return 0; } ``` 此方法使用`strlen`函数获取字符数组的长度,遍历字符数组,将小写字母转换大写字母并输出[^4]。 ### 方法五:通过ASCII码转换 ```cpp #include <iostream> using namespace std; int main() { char a[1001]; cin >> a; int i = 0; while (a[i]) { if (a[i] >= 'a' && a[i] <= 'z') { a[i] = a[i] - 'a' + 'A'; } cout << a[i]; i++; } return 0; } ``` 该方法通过`while`循环遍历字符数组,将小写字母转换大写字母并输出,转换使用`a[i] - 'a' + 'A'`的方式[^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值