c++遍历字符串

c++ looping through string

本文关键字:字符串 遍历 c++      更新时间:2023-10-16

最后,我找到了将小写转换为大写的解决方案,并确定字符串是字母还是数字代码,如下所示:

#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