Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- void printNumCharacters (const std::string& sentence); //Prints number of characters.
- void printNumWords (const std::string& sentence); //Prints number of words.
- void printToUpper (const std::string& sentence); //Prints sentence to upper case.
- void printSubString (const std::string& sentence); //Prints a sub string.
- int main()
- {
- std::string sentence;
- std::cout << "Please enter a sentence. \n";
- std::getline(std::cin, sentence);
- printNumCharacters (sentence);
- printNumWords (sentence);
- printToUpper (sentence);
- printSubString (sentence);
- return 0;
- }
- void printNumCharacters(const std::string& sentence)
- {
- std::cout << "Number of characters: " << sentence.length() << std::endl;
- }
- void printNumWords(const std::string& sentence)
- {
- char letter;
- int words;
- unsigned int i = 0;
- while(std::isspace(sentence.at(i))) { //Count spaces at start of sentence if any
- i++;
- }
- sentence.empty() ? words = 0 : words = 1; //Ternary operator! We need to do this as the following loop counts the spaces, rather than the words
- //If the string is empty, then words = 0 : If not, then count the first word
- for (; i < sentence.length(); i++) //Simple "for loop" to iterate through each character of the string
- {
- letter = sentence[i];
- if( letter == ' ')
- {
- words++;
- }
- }
- std::cout << "Number of words: " << words << std::endl;
- }
- void printToUpper(const std::string& sentence)
- {
- std::locale loc;
- for (std::string::size_type i = 0 ; i< sentence.length(); i++)
- {
- std::cout << std::toupper(sentence[i], loc); //I literally Googled this one lol
- }
- std::cout << "\n";
- }
- void printSubString(const std::string& sentence)
- {
- unsigned start = 0;
- unsigned int end = sentence.length() + 1;
- std::cout << "Enter where you want to start printing the string (Character number) between 0 and " << sentence.length() << std::endl;
- do { //"Do while loop"
- std::cin >> start;
- if( start < 0) std::cout << "Too small! Enter number greater than 0!" << std::endl;
- if( start > sentence.length()) std::cout << "Too big! Enter number less than " << sentence.length() << "!" << std::endl;
- } while ( start < 0 || start > sentence.length() );
- std::cout << "Enter where you want to end printing the string (Character number) between " << start << " and " << sentence.length() << std::endl;
- do { //"Do while loop"
- std::cin >> end;
- if( start < start) std::cout << "Too small! Enter number greater than 0!" << start << "!" << std::endl;
- if( start > sentence.length()) std::cout << "Too big! Enter number less than " << sentence.length() << "!" << std::endl;
- } while ( end < start || end > sentence.length() );
- std::cout << sentence.substr(start, end); //Built in!
- }
Advertisement
Add Comment
Please, Sign In to add comment