c++ string startwith方法使用



#include <iostream>
using namespace std;
 
int main()
{
    string s("hello, world");
    string head("hello");
    string tail("ld");
    bool startwith = s.compare(0, head.size(), head) == 0;
    cout << boolalpha << startwith << endl;
    bool endwith = s.compare(s.size() - tail.size(), tail.size(), tail) == 0;
    cout << boolalpha << endwith << endl;
}




### C++ 中的字符串处理 在 C++ 中,`std::string` 是用于表示和操作字符序列的标准库类。此容器提供了一系列成员函数来执行各种字符串操作。 #### 创建字符串对象 可以使用多种方式创建 `std::string` 对象: ```cpp #include <iostream> #include <string> int main() { std::string str1 = "Hello"; // 使用字面量初始化 std::string str2(str1); // 复制构造函数 std::string str3(5, 'a'); // 构造指定长度并填充特定字符 std::cout << str1 << "\n"; std::cout << str2 << "\n"; std::cout << str3 << "\n"; return 0; } ``` #### 字符串连接 可以通过运算符 `+` 或者成员方法 `append()` 来拼接两个字符串[^1]。 ```cpp #include <iostream> #include <string> int main() { std::string first_name = "John", last_name = "Doe"; // 运算符 + std::string full_name = first_name + " " + last_name; // 成员函数 append() std::string another_full_name = first_name.append(" ").append(last_name); std::cout << full_name << "\n"; std::cout << another_full_name << "\n"; return 0; } ``` #### 查找子串位置 利用 `find()` 方法可以在源字符串内搜索给定模式的位置索引;如果未找到,则返回 `npos` 值。 ```cpp #include <iostream> #include <string> int main() { std::string text = "The quick brown fox jumps over the lazy dog."; size_t pos = text.find("fox"); if (pos != std::string::npos) { std::cout << "'fox' found at position: " << pos << '\n'; } else { std::cout << "'fox' not found\n"; } return 0; } ``` #### 替换部分字符串内容 通过调用 `replace()` 函数可替换原有字符串中的某一部分为新的内容。 ```cpp #include <iostream> #include <string> int main() { std::string sentence = "I love programming with Python!"; int start_pos = 7; // 开始替换的位置 int num_chars_to_replace = 9; // 被替换单词的数量 const char* new_word = "coding"; sentence.replace(start_pos, num_chars_to_replace, new_word); std::cout << sentence << "\n"; return 0; } ``` #### 提取子串 借助于 `substr()` 可轻松获取原字符串的一个片段作为新字符串实例。 ```cpp #include <iostream> #include <string> int main() { std::string long_string = "This is a very long string that we will use to demonstrate substrings."; // 获取从第8个字符开始到结尾的所有字符组成的子串 std::string sub_str_1 = long_string.substr(8); // 获取从第8个字符开始连续10个字符组成的新字符串 std::string sub_str_2 = long_string.substr(8, 10); std::cout << "Substring from index 8 till end:\n" << sub_str_1 << "\n\n"; std::cout << "Substring starting at index 8 of length 10 characters:\n" << sub_str_2 << "\n"; return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值