string 类在多种编程语言中都有实现,例如 C++, Java, C#, Python 等。每种语言
中的 string 类提供的方法可能有所不同,但通常都包含一些基本的、通用的操
作。以下是一些常见的 string 类方法,以 C++ 和 Java 为例进行说明:
C++ 中的 std::string 类常用方法:
1. 构造函数:
o std::string():默认构造函数,创建一个空字符串。
o std::string(const char* s):用 C 风格字符串初始化。
o std::string(size_t n, char c):用 n 个字符 c 初始化。
2. 访问和修改:
o char& operator[](size_t pos):返回指定位置的字符的引用。
o char at(size_t pos) const:返回指定位置的字符。
o void push_back(char c):在字符串末尾添加一个字符。
o void append(const std::string& str):在字符串末尾添加另一个字
符串。
3. 比较:
o bool operator==(const std::string& str) const:比较两个字符串是
否相等。
o bool operator<(const std::string& str) const:比较两个字符串是
否小于。
o int compare(const std::string& str) const:比较两个字符串,返回
小于、等于或大于零的值。
4. 大小和容量:
o size_t size() const:返回字符串中的字符数。
o size_t length() const:与 size() 功能相同。
o bool empty() const:检查字符串是否为空。
o size_t capacity() const:返回当前分配的存储容量。
5. 修改:
o void replace(size_t pos, size_t count, const std::string& str):
替换子字符串。
o void erase(size_t pos = 0, size_t count = npos):删除子字符串。
o std::string substr(size_t pos = 0, size_t count = npos) const:返
回子字符串。
6. 查找和搜索:
o size_t find(const std::string& str, size_t pos = 0) const:查找
子字符串的位置。
o size_t find_first_of(const std::string& str, size_t pos = 0)
const:查找任何给定字符首次出现的位置。
o size_t find_last_of(const std::string& str, size_t pos = npos)
const:查找任何给定字符最后一次出现的位置。
Java 中的 String 类常用方法: