簡體   English   中英

C ++遍歷字符串

[英]c++ looping through string

最后,我找到了將lowecase轉換為大寫並確定字符串是字母還是數字代碼的解決方案,如下所示:

#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();
} 

如何改進上面的代碼以獲取字符串而不是單個字符? 循環使打印相同的語句多次。 謝謝

冷杉使用輸入運算符讀取字符串:

std::string input;
std::cin >> input;

(可選)您可以使用std::getline獲得多個單詞。

然后,您可以使用std::transform將字符串轉換為大寫或小寫形式。

您還可以使用基於范圍的for循環來迭代字符串中的字符。

更新:這是更清潔的解決方案,可以輸出一個單詞。

#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 :: transform


只需閱讀整個單詞,然后使用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();
}

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進行編譯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM