续:string的用法 1、字符串插入 2、c_str 3、分隔后缀 4、字符串转化为数值,或数值转化为字符串
1、字符串插入
# define _CRT_SECURE_NO_WARNINGS
# include <iostream>
# include <string>
# include <assert.h>
using namespace std; void test_string8 ( )
{ string str ( "wo lai le" ) ; for ( size_t i = 0 ; i < str. size ( ) ; ++ i) { if ( ' ' == str[ i] ) { str. insert ( i, "20%" ) ; i += 4 ; } else { ++ i; } } cout << str << endl; for ( size_t i = 0 ; i < str. size ( ) ; ++ i) { if ( ' ' == str[ i] ) { str. insert ( i, "20%" ) ; i += 3 ; } } cout << str << endl; for ( size_t i = 0 ; i < str. size ( ) ; ++ i) { if ( ' ' == str[ i] ) { str. erase ( i, 1 ) ; } } cout << str << endl; string newstr; for ( size_t i = 0 ; i < str. size ( ) ; ++ i) { if ( str[ i] != ' ' ) { newstr += str[ i] ; } else { newstr += "20%" ; } } cout << newstr << endl; }
2、c_str
void test_string9 ( )
{ string filename ( "test.cpp" ) ; cout << filename << endl; cout << filename. c_str ( ) << endl; filename += '\0' ; filename += "string.cpp" ; cout << filename << endl; cout << filename. c_str ( ) << endl; cout << filename. size ( ) << endl; string copy = filename; cout << copy << endl;
}
3、分隔后缀
void DealUrl ( const string& url)
{ size_t pos1 = url. find ( "://" ) ; if ( pos1 == string:: npos) { cout << "非法url" << endl; return ; } string protocol = url. substr ( 0 , pos1) ; cout << protocol << endl; size_t pos2 = url. find ( '/' , pos1 + 3 ) ; if ( pos2 == string:: npos) { cout << "非法url" << endl; return ; } string domain = url. substr ( pos1 + 3 , pos2 - pos1 - 3 ) ; cout << domain << endl; string uri = url. substr ( pos2 + 1 ) ; cout << uri << endl; } void test_string10 ( )
{ string url1 = "https://cplusplus.com/reference/string/string/" ; string url2 = "ftp://ftp.cs.umd.edu/pub/skipLists/skiplists.pdf" ; DealUrl ( url1) ; cout << endl; DealUrl ( url2) ; }
4、字符串转化为数值,或数值转化为字符串
void test_string12 ( )
{ int ival; double dval; cin >> ival >> dval; string istr = to_string ( ival) ; string dstr = to_string ( dval) ; cout << istr << endl; cout << dstr << endl; istr = "9999" ; dstr = "9999.99" ; ival = stoi ( istr) ; dval = stod ( dstr) ; cout << ival << endl; cout << dval << endl;
} int main ( )
{ test_string12 ( ) ; return 0 ;
}