Accessing Characters In Strings : String « Data Type « C++






Accessing Characters In Strings

Accessing Characters In Strings
 
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
   string text;                  
          
   cout << "Counts words. Enter a text and terminate with a period and return:\n";
   
   getline( cin, text, '.');     // Reads a text up to the first '.'

   int  i,                             // Index

        numberOfWhiteSpace = 0,        // Number of white spaces

        numberOfWords  = 0;            // Number of words

   bool fSpace = true;                 // Flag for white space
   for( i = 0; i < text.length(); ++i)
   {
      if( isspace( text[i]) )          // white space?
      {
         ++numberOfWhiteSpace;  
         fSpace = true;
      }
      else if( fSpace)                 // At the beginning of a word?
      {
         ++numberOfWords;   
         fSpace = false;
      }
   }
   cout << "\nYour text contains (without periods)"
        << "\ncharacters: " << text.length()
        << "\nwords: " << numberOfWords
        << "\nwhite spaces: " << numberOfWhiteSpace
        << endl;
   return 0;
} 


           
         
  








Related examples in the same category

1.String type classString type class
2.A filter to remove white-space characters at the ends of lines.A filter to remove white-space characters at the ends of lines.
3.A string demonstration: assignment, concatenate, compareA string demonstration: assignment, concatenate, compare
4.Demonstrate insert(), erase(), and replace().Demonstrate insert(), erase(), and replace().
5.Use string: find, string::nposUse string: find, string::npos
6.Strings: size, iterator, count, begin and endStrings: size, iterator, count, begin and end
7.string: find( ) and rfind( )string: find( ) and rfind( )
8.Print a name in two different formatsPrint a name in two different formats
9.Several string operations: substrSeveral string operations: substr
10.String Char IndexingString Char Indexing
11.String Find and replaceString Find and replace
12.String SizeString Size
13.String SizeOfString SizeOf
14.A short string demonstrationA short string demonstration
15.String insert(), erase(), and replace()String insert(), erase(), and replace()
16.string variable instead of a character arraystring variable instead of a character array
17.Inputting Multiple Words into a StringInputting Multiple Words into a String
18.Adding StringsAdding Strings
19.Read string from consoleRead string from console
20.Insert, search, and replace in strings.Insert, search, and replace in strings.