C++/String/string iterator

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Access the contents of a string using iterators

  
#include <string>
#include <iostream>
int main(){
   using namespace std;
   string str ("Hello String");
   int i = 0;
   string::const_iterator itt;
   for ( itt = str.begin (); itt != str.end (); ++ itt )
   {
       cout << "Character [" << i ++ << "] is: ";
       cout << *itt << endl;
   }
   //The char* representation of the string is: "
   cout << str.c_str () << endl;
   return 0;
}


Create an iterator to a string and Use it to cycle through the characters of a string

  
#include <iostream>
#include <string>
#include <cctype>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
  string strA("This is a test.");
  string::iterator itr;
  
  for(itr = strA.begin(); itr != strA.end(); ++itr)
    cout << *itr;
  return 0;
}


increment the iterator

  
#include <iostream>
#include <string>
#include <cctype>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
  string strA("This is a test.");
  string::iterator itr;
  itr = find(strA.begin(), strA.end(), "a");
  ++itr;
  return 0;
}


string::npos

  
 
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
int main() {
  string text = "asdf asdf asdf asdf asdf";
  size_t start = text.find_first_not_of("df");
  
  cout << start;
  cout << string::npos;
  return 0;
}
/* 
04294967295
 */


use iterator

  
 

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
  string str1("Strings handling is easy in C++");
  string::iterator p;
  unsigned int i;
  // use iterator
  p = str1.begin();
  while(p != str1.end()) 
    cout << *p++;
  cout << endl;

  return 0;
}
/* 
Strings handling is easy in C++
 */


Using an iterator to output a string

  
 
#include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
int main()
{
   string string1( "Testing iterators" );
   string::const_iterator iterator1 = string1.begin();
   cout << "string1 = " << string1
      << "\n(Using iterator iterator1) string1 is: ";
   while ( iterator1 != string1.end() ) 
   {
      cout << *iterator1; 
      iterator1++;        
   }
   cout << endl;
   return 0;
}
/* 
string1 = Testing iterators
(Using iterator iterator1) string1 is: Testing iterators
 */