c++遍历字符串
c++ looping through string
最后,我找到了将小写转换为大写的解决方案,并确定字符串是字母还是数字代码,如下所示:
#include <cctype>
#include <iostream>
using namespace std;
int main()
{
char ch;
cout<<"Enter a character: ";
gets(ch);
if ( isalpha ( ch ) ) {
if ( isupper ( ch ) ) {
ch = tolower ( ch );
cout<<"The lower case equivalent is "<< ch <<endl;
}
else {
ch = toupper ( ch );
cout<<"The upper case equivalent is "<< ch <<endl;
}
}
else
cout<<"The character is not a letter"<<endl;
cin.get();
}
我如何改进上面的代码,以获得字符串而不是单个字符?循环保持多次打印相同的语句。由于
更新:这是一个更简洁的解决方案,输出一个单词。
#include <cctype>
#include <iostream>
#include <algorithm>
using namespace std;
char switch_case (char ch) {
if ( isalpha ( ch ) ) {
if ( isupper ( ch ) ) {
return tolower ( ch );
}
else {
return toupper ( ch );
}
}
return '-';
}
int main()
{
string str;
cout<<"Enter a word: ";
cin >> str;
transform(str.begin(), str.end(), str.begin(), switch_case);
cout << str << "n";
}
在这个例子中使用了std::转换。
读取整个单词并使用std::string::iterator每次迭代一个字母:
#include <cctype>
#include <iostream>
using namespace std;
int main()
{
string str;
cout<<"Enter a word: ";
cin >> str;
for ( string::iterator it = str.begin(); it != str.end(); ++it ) {
char ch = *it;
if ( isalpha ( ch ) ) {
if ( isupper ( ch ) ) {
ch = tolower ( ch );
cout<<"The lower case equivalent is "<< ch <<endl;
}
else {
ch = toupper ( ch );
cout<<"The upper case equivalent is "<< ch <<endl;
}
}
else
cout<<"The character is not a letter"<<endl;
}
cin.get();
}
首先使用输入操作符读入字符串:
std::string input;
std::cin >> input;
您可以选择使用std::getline
来获取多个单词。
然后您可以使用std::transform
将字符串转换为大写或小写。
还可以使用基于范围的for循环遍历字符串中的字符。
c++ 11:
#include <cctype>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
cout << "Enter data: ";
cin >> s;
for (auto &ch : s)
{
if (isalpha(ch))
{
if (isupper(ch))
{
ch = tolower(ch);
cout << "The lower case equivalent is " << ch << endl;
}
else
{
ch = toupper(ch);
cout << "The upper case equivalent is " << ch << endl;
}
}
else
cout << "The character is not a letter" << endl;
};
cin.get();
}
或
#include <cctype>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string s;
cout << "Enter a string: ";
cin >> s;
transform(s.begin(), s.end(), s.begin(), [](char ch)
{
return isupper(ch)? tolower(ch) : toupper(ch);
});
}
如果您有g++
,请尝试编译:g++ test.cpp -o test -std=c++11
相关文章:
- 有什么方法可以遍历结构吗
- 在循环中按顺序遍历成员变量
- 遍历模板参数
- 广义后缀树遍历以查找最长的公共子字符串
- 在遍历字符串时,为什么我没有超出范围错误,即使我已经超出了它的长度?
- 如何遍历特定字符串的向量
- 在C 中的字符串向量的字符串元素中循环遍历所有字符
- 是否可以遍历文本文件行并使用字符串流来解析每一行
- 在字符串数组中遍历每个字符
- 如何遍历整个字符串并一次播放一个字符C++
- 通过指针循环遍历字符串数组
- 如何遍历字符串中的所有utf-8代码点
- 在C++中遍历字符串
- 通过指针增量遍历C字符串
- 无法使用迭代器遍历字符串:但是我的带有索引的版本确实有效
- 如何使用find()遍历字符串
- 遍历C++中的字符串列表,出了什么问题?
- 如何遍历 std::vector<char> 并查找以 null 结尾的 c 字符串
- c++遍历字符串
- 逐个字符遍历字符串字符