#include <iostream>
#include "string"
using namespace std;
void strInit ( )
{
cout << "字符串初始化:" << endl;
string s1 = "abcdefg" ;
string s2 ( "abcdefg" ) ;
string s3 = s2;
string s4 ( 7 , 's' ) ;
cout << "s1 = " << s1 << endl;
cout << "s2 = " << s2 << endl;
cout << "s3 = " << s3 << endl;
cout << "s4 = " << s4 << endl;
}
void strErgo ( )
{
cout << "字符串遍历:" << endl;
string s1 = "abcdefg" ;
cout << "1、通过数组方式遍历:" << endl;
for ( int i = 0 ; i < s1. length ( ) ; i++ )
{
cout << s1[ i] << " " ;
}
cout << endl;
cout << "2、通过迭代器遍历:" << endl;
for ( string: : iterator it = s1. begin ( ) ; it!= s1. end ( ) ; it++ )
{
cout << * it << " " ;
}
cout << endl;
cout << "3、通过at()方式遍历:" << endl;
for ( int i = 0 ; i < s1. length ( ) ; i++ )
{
cout << s1. at ( i) << " " ;
}
cout << endl;
}
void strConvert ( )
{
cout << "字符指针和字符串的转换:" << endl;
string s1 = "abcdefg" ;
cout << "string转换为char*:" << endl;
cout << s1. c_str ( ) << endl;
cout << "char*获取string内容:" << endl;
char buf[ 64 ] = { 0 } ;
s1. copy ( buf, 7 ) ;
cout << buf << endl;
}
void strAdd ( )
{
cout << "字符串连接:" << endl;
cout << "方式1:" << endl;
string s1 = "123" ;
string s2 = "456" ;
s1 + = s2;
cout << "s1 = " << s1 << endl;
cout << "方式2:" << endl;
string s3 = "123" ;
string s4 = "456" ;
s3. append ( s4) ;
cout << "s3 = " << s3 << endl;
}
int main ( )
{
strInit ( ) ;
cout << endl;
strErgo ( ) ;
cout << endl;
strConvert ( ) ;
cout << endl;
strAdd ( ) ;
cout << endl;
system ( "pause" ) ;
return 0 ;
}
结果
字符串初始化:
s1 = abcdefg
s2 = abcdefg
s3 = abcdefg
s4 = sssssss
字符串遍历:
1 、通过数组方式遍历:
a b c d e f g
2 、通过迭代器遍历:
a b c d e f g
3 、通过at ( ) 方式遍历:
a b c d e f g
字符指针和字符串的转换:
string转换为char * :
abcdefg
char * 获取string内容:
abcdefg
字符串连接:
方式1 :
s1 = 123456
方式2 :
s3 = 123456
原文地址-------------------||-----------------------