C++/String/string subscript indexer
Содержание
Accessing characters in a string
<source lang="cpp">
- 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.
*/ </source>
Modify char in a string by indexer
<source lang="cpp">
- 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:
*/ </source>
switch statement based on char value
<source lang="cpp">
- 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.
*/ </source>
Tests whether a string is a palindrome
<source lang="cpp">
- 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;
}
</source>