如何在C++中获取子字符串并在字符串之间添加字符
How to get substring in C++ and add character in between string
我有一个字符串 你好,你好吗。
我想把它改成你好\rfoo你好吗。
我想知道获取子字符串 Hello 添加 \r 代替空格并按原样添加所有其他字符串的方法。这是为了显示多行。
编辑:
我们不知道第一个子字符串的长度。我们不知道第一个子字符串会有多长。
谢谢。
不是一个完整的答案,因为这看起来像家庭作业,但您可以使用的其他方法包括<algorithm>
中的std::find()
和<string.h>
中的strchr()
。 如果您需要搜索任何空格,而不仅仅是' '
字符,则可以使用std::find_first_of()
或strcspn()
。
将来,我会查看以下文档:std::basic_string
的成员函数、<string>
中的实用程序函数、<algorithm>
中的函数和<string.h>
中的函数,因为这些通常是您必须使用的工具。
#include <iostream>
#include <string>
int main() {
std::string s = "Hello foo how are you.";
s.replace(s.find_first_of(" "),1,"rn");
std::cout << s << std::endl; #OUTPUTS: "Hello
# foo how are you."
return 0;
}
这里你要用的是string::replace(pos,len,insert_str);
,这个函数允许你用你的"rn"
替换s
中指定的子字符串。
编辑:您希望使用s.find_first_of(str)
查找字符串的第一个匹配项" "
要获得子字符串,您的答案在于函数 string::substr:
string::substr (size_t pos = 0, size_t len = npos) const;
- POS参数是要复制为子字符串的第一个字符的索引。
- len参数是从索引开始的子字符串中要包含的字符数。
返回一个新实例化的字符串对象,其值是调用它的指定字符串对象的子字符串。
// Example:
#include <iostream>
#include <string>
int main () {
std::string str1= "Hello Stack Overflow";
std::string str2 = str.substr (0,5); // "Hello
std::cout << str2 << std::endl; // Prints "Hello"
return 0;
}
>UPDATE:但是它看起来与您的标题不同,您需要在不知道子字符串长度的情况下更改一些字符为此,您的答案是字符串::替换:
string& replace (size_t pos, size_t len, const string& str);
替换字符串中从索引 pos 开始并上升到索引 len 的部分。
- POS参数是要替换的第一个字符的索引。
- len参数是从索引开始要替换的字符数。
- 要替换它的 str 字符串参数。
// Example
int main()
std::string str = "Hello Stack Overflow.";
std::string str2 = "good";
str.replace(6, 4, str2); // str = "Hello goodStackOverflow"
return 0;
}
在某些编译器中,您可能不需要添加它,但您需要包含字符串标头,以确保您的代码可移植且可维护:
#include <string>
相关文章:
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 尝试将字符串/字符转换为整数会产生意外结果
- 为什么没有访问所有字符串字符?
- 将子字符串字符从字符串值转换为 int,然后将其分配给 int 变量
- 如何将字符串字符与结构数组进行比较?
- 将单个字符串/字符输入串行监视器
- 读取字符串字符时出错 - 对于数组中的字符串值
- C++ C 样式字符串/字符数组的大小 - 优化
- 读取字符串字符时出错
- C++ 使用 Strtok 读取字符串字符时出错
- 如何将 int 数组的 1 个元素转换为字符串/字符
- 在另一个字符串中逐个复制字符串字符
- 将字符串字符映射到矢量
- MBED RTOS将Float转换为字符串/字符阵列
- 如何使用字符串字符数组中的 ++ 运算符访问下一个字符串
- 如何比较C++中的单个字符串字符?
- 内部字符串/字符如何在 int 和 float 中存储
- 将十六进制转换为可打印的字符串/字符
- wcscpy_s后读取字符串字符时出错
- 检查字符串字符和长度