C++/String/string subscript indexer

Материал из C\C++ эксперт
Версия от 10:25, 25 мая 2010; Admin (обсуждение | вклад) (1 версия: Импорт контента...)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Accessing characters in a string

  
 
#include <iostream>
#include <string>
#include <cctype>
using std::cout;
using std::cin;
using std::endl;
using std::string;
int main() {
  string text = "asdffdsaasdf";

  int vowels = 0;              
  int consonants = 0;          
  for(int i = 0 ; i < text.length() ; i++)
    if(std::isalpha(text[i]))  
      switch(std::tolower(text[i])) {
        case "a": case "e": case "i":
        case "o": case "u":
          vowels++;
          break;
        default:
          consonants++;
      }
  cout << "Your input contained "
       << vowels     << " vowels and "
       << consonants << " consonants."
       << endl;
  return 0;
}
/* 
Your input contained 3 vowels and 9 consonants.
 */


Modify char in a string by indexer

  
 
#include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
int main()
{
   string string1( "cat" );
   string string2;
   string string3;
   string2 = string1;
   string3.assign( string1 );
   
   cout << "string1: " << string1 << "\nstring2: " << string2
      << "\nstring3: " << string3 << "\n\n";
   string2[ 0 ] = string3[ 2 ] = "r";
   cout << "string1: " << string1 << "\nstring2: " << string2 << "\nstring3: ";

   return 0;
}
/* 
string1: cat
string2: cat
string3: cat
string1: cat
string2: rat
string3: 
 */


switch statement based on char value

  
 
#include <iostream>
#include <string>
#include <cctype>
using std::cout;
using std::cin;
using std::endl;
using std::string;
int main() {
  string text = "asdffdsaasdf";

  int vowels = 0;              
  int consonants = 0;          
  for(int i = 0 ; i < text.length() ; i++)
    if(std::isalpha(text[i]))  
      switch(std::tolower(text[i])) {
        case "a": case "e": case "i":
        case "o": case "u":
          vowels++;
          break;
        default:
          consonants++;
      }
  cout << "Your input contained "
       << vowels     << " vowels and "
       << consonants << " consonants."
       << endl;
  return 0;
}
/* 
Your input contained 3 vowels and 9 consonants.
 */


Tests whether a string is a palindrome

  
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool is_palindrome(string s)
{
   if (s.length() <= 1) 
     return true;
   char first = s[0];
   char last = s[s.length() - 1];
   if (first == last){
      string subString = s.substr(1, s.length() - 2);
      return is_palindrome(subString);
   }
   else
      return false;
}
int main()
{
   cout << "Enter a string: ";
   string input;
   getline(cin, input);
   if (!is_palindrome(input)) 
     cout << "false";
   
   return 0;
}