Advertisement
atimholt

c++ String question

Dec 17th, 2012
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | None | 0 0
  1.  
  2. #include <iostream>
  3. #include <array>
  4. #include <string>
  5.  
  6. using namespace std;
  7.  
  8. int main()
  9. {
  10.   // stl array string.
  11.   array<char,7> stl_array_string {"He\0llo"};
  12.  
  13.   int null_count {0};
  14.  
  15.   for ( const auto& a_char : stl_array_string )
  16.   {
  17.     if ( a_char == '\0' )
  18.       ++null_count;
  19.   }
  20.   cout << "null chars iterated over in strange stl array string: " << null_count << endl;
  21.   // cout << "Streams as \"" << stl_array_string << "\"." << endl;
  22.   // Doesn't compile, but given that that's not what it's for, I'm not surprised.
  23.  
  24.  
  25.   // c-style array string
  26.   char c_style_array_string[] {"He\0llo"};
  27.   null_count = 0;
  28.   for ( const auto& a_char : c_style_array_string )
  29.   {
  30.     if ( a_char == '\0' )
  31.       ++null_count;
  32.   }
  33.   cout << "null chars iterated over in c-style, array based string: " << null_count << endl;
  34.   cout << "Streams as \"" << c_style_array_string << "\"." << endl;
  35.  
  36.  
  37.   // standard string
  38.   string standard_string {"He\0llo"};
  39.   null_count = 0;
  40.   for ( const auto& a_char : standard_string  )
  41.   {
  42.     if ( a_char == '\0' )
  43.       ++null_count;
  44.   }
  45.   cout << "null chars iterated over in standard string: " << null_count << endl;
  46.   cout << "Streams as \"" << standard_string << "\"." << endl;
  47.  
  48.   return 0;
  49.  
  50.   // Output is:
  51.   //null chars iterated over in strange stl array string: 2
  52.   //null chars iterated over in c-style, array based string: 2
  53.   //Streams as "He".
  54.   //null chars iterated over in standard string: 0
  55.   //Streams as "He".
  56.  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement