在C++中, std::string 類有許多常用函數,以下是一些常見的:
1. length() 或 size() :返回字符串的長度(字符個數),二者功能相同。例如:
# include <iostream>
# include <string>
int main ( ) { std:: string str = "hello" ; std:: cout << str. length ( ) << std:: endl; std:: cout << str. size ( ) << std:: endl; return 0 ;
}
2. empty() :檢查字符串是否為空,為空返回 true ,否則返回 false 。
# include <iostream>
# include <string>
int main ( ) { std:: string str1 = "" ; std:: string str2 = "world" ; std:: cout << std:: boolalpha << str1. empty ( ) << std:: endl; std:: cout << std:: boolalpha << str2. empty ( ) << std:: endl; return 0 ;
}
3. append() :在字符串末尾追加另一個字符串或字符序列。
# include <iostream>
# include <string>
int main ( ) { std:: string str = "hello" ; str. append ( " world" ) ; std:: cout << str << std:: endl; return 0 ;
}
pop_back():刪除字符串最后一個字符
str。pop_back ( ) :
4. substr() :返回字符串的子串。接受起始位置和長度作為參數。
cpp# include <iostream>
# include <string>
int main ( ) { std:: string str = "hello world" ; std:: string sub = str. substr ( 0 , 5 ) ; std:: cout << sub << std:: endl; return 0 ;
}
5. find() :在字符串中查找指定子串或字符的位置,返回首次出現的位置索引,若未找到返回 std::string::npos 。
cpp
# include <iostream>
# include <string>
int main ( ) { std:: string str = "hello world" ; size_t pos = str. find ( "world" ) ; if ( pos != std:: string:: npos) { std:: cout << "子串位置: " << pos << std:: endl; } return 0 ;
}
6. replace() :用新的子串替換字符串中指定的子串。
# include <iostream>
# include <string>
int main ( ) { std:: string str = "hello world" ; str. replace ( 6 , 5 , "C++" ) ; std:: cout << str << std:: endl; return 0 ;
}
7. c_str() :返回一個指向以空字符結尾的C風格字符串的指針。常用于與C語言函數接口。
# include <iostream>
# include <string>
# include <cstdio>
int main ( ) { std:: string str = "hello" ; const char * cstr = str. c_str ( ) ; printf ( "%s\n" , cstr) ; return 0 ;
}