C++/String/string at

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

Accessing Character Elements of an STL String

  
#include <string>
#include <iostream>
int main(){
   using namespace std;
   string str ("Hello String");
   for(size_t i = 0; i < str.length(); ++ i){
       cout << "Character [" << i << "] is: ";
       cout << str [i] << endl;
   }
   cout << endl;
   return 0;
}


Demonstrating member function at

  
 
#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";
   // demonstrating member function at
   for ( int i = 0; i < string3.length(); i++ ) 
      cout << string3.at( i );
   return 0;
}
/* 
string1: cat
string2: cat
string3: cat
cat"
 */


Display the characters in a string one at a time by using the indexing operator

  
#include <iostream>
#include <string>
using namespace std;
int main()
{
  string str1("A");
  string str2("B");
  string str3("G");
  string str4;
  cout << "  str1: " << str1 << endl;
  cout << "  str2: " << str2 << endl;
  cout << "  str3: " << str3 << "\n\n";
  for(unsigned i = 0; i < str1.size(); ++i)
    cout << "str1[i]: " << str1[i] << endl;
  cout << endl;
  return 0;
}


Get a C-Style String from a C++ String

  
#include <cstdio>
#include <string> 
using namespace std; 
int main( )
{
   string boss( "B" );
   printf( "%s is an important man.\n\n", boss.c_str() ); 
   char man[50];
   strcpy( man, boss.c_str() );
   strupr( man );
   printf( "this is a test: %s\n", man );
}