字符串验证

时间:2017-10-02 07:22:41

标签: c++ string validation input

如何验证字符串以检查它是否只有大写字母?你如何检查它是否包含大写和小写字母?

cout << "Enter state name or state abbr:" << " " << endl;
cin >> st;

if ((st == stateArray[in].getStateAbbr()) && (std::all_of(st.begin(), st.end(), isupper))) // uppercase only
{
    cout << "Found. Your string is a state abbr." << endl;
}
else if ((st == stateArray[in].getStateName()) ) 
{
    cout << "Found." << " Your string is a state name" << endl;
}
else
{
    cout << "Not found" << endl;
}

1 个答案:

答案 0 :(得分:0)

  

如何验证字符串以检查它是否只有大写字母?你如何检查它是否包含大写和小写字母?

如果您只有ASCII字符,则可以执行以下操作:

std::string st;
getline(std::cin, st);

然后:

//check all uppercase
bool upperCase = true;

for (char c : st)
{
   if (c < 65 || c > 90)
   {
      upperCase = false;
      break;
   }
}

//check all lowercase
bool lowerCase = true;

for (char c : st)
{
   if (c < 97 || c > 122)
   {
      lowerCase = false;
      break;
   }
}

//check both uppercase and lowercase
bool both = true;

for (char c : st)
{
   if ((c < 65) || (c > 90 && c < 97) || (c > 122))
   {
      both = false;
      break;
   }
}

然后你可以检查bool变量:

if (upperCase) std::cout << "All chars are upper case." << std::endl;
if (lowerCase) std::cout << "All chars are lower case." << std::endl;
if (both)      std::cout << "All chars are upper case or lower case." << std::endl;