1. 字符串与整数之间的转换
字符串转整数
使用 std::stoi
将字符串转换为整数。 使用 std::stol
将字符串转换为长整型。 使用 std::stoul
将字符串转换为无符号长整型。
std:: string strNum = "12345" ;
int num = std:: stoi ( strNum) ;
long long numLong = std:: stoll ( strNum) ;
unsigned long long numUnsigned = std:: stoull ( strNum) ;
整数转字符串
使用 std::to_string
将整数转换为字符串。
int num = 12345 ;
std:: string strNum = std:: to_string ( num) ;
2. 字符串与浮点数之间的转换
字符串转浮点数
使用 std::stof
将字符串转换为 float
。 使用 std::stod
将字符串转换为 double
。 使用 std::stold
将字符串转换为 long double
。
std:: string strFloat = "123.45" ;
float floatVal = std:: stof ( strFloat) ;
double doubleVal = std:: stod ( strFloat) ;
long double longDoubleVal = std:: stold ( strFloat) ;
浮点数转字符串
使用 std::to_string
将浮点数转换为字符串。
double num = 123.456 ;
std:: string strNum = std:: to_string ( num) ;
3. 常见的字符串函数
检查字符串长度
使用 length()
或 size()
函数获取字符串长度。
std:: string str = "Hello, World!" ;
size_t len = str. length ( ) ;
字符串拼接
使用 +
运算符或 append()
方法拼接字符串。
std:: string str1 = "Hello, " ;
std:: string str2 = "World!" ;
std:: string str3 = str1 + str2;
str1. append ( str2) ;
字符串查找
std:: string str = "Hello, World!" ;
size_t pos = str. find ( "World" ) ;
字符串替换
使用 replace()
函数替换字符串的一部分。
std:: string str = "Hello, World!" ;
str. replace ( str. find ( "World" ) , 5 , "Universe" ) ;
字符串删除
std:: string str = "Hello, World!" ;
str. erase ( str. find ( "World" ) , 5 ) ;
字符串插入
使用 insert()
函数在指定位置插入字符串。
std:: string str = "Hello, " ;
str. insert ( 7 , "World!" ) ;
字符串比较
std:: string str1 = "abc" ;
std:: string str2 = "def" ;
if ( str1 < str2) {
std:: cout << "str1 is less than str2" << std:: endl;
} else if ( str1 > str2) {
std:: cout << "str1 is greater than str2" << std:: endl;
} else {
std:: cout << "str1 is equal to str2" << std:: endl;
}
字符串分割
使用 std::getline()
和 std::istringstream
分割字符串。
std:: string line = "one,two,three" ;
std:: stringstream ss ( line) ;
std:: string item;
while ( getline ( ss, item, ',' ) ) {
std:: cout << item << std:: endl;
}