如何将字符串与一个字符交错?
How to interlace string with one character?
我需要编写一个函数,例如用"s't'r'i'n'g"
替换例如"string"
。
我将字符串添加到数组中,然后... 下一步是什么?
我的代码:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string x;
cout << "Type a string: ";
cin >> x;
char array[x.length()];
for (int i = 0; i < sizeof(array); i++) {
array[i] = x[i];
cout << array[i];
}
}
我将字符串添加到数组中
这是你的第一个错误。您不会在 C++ 中使用字符串数组,而是使用std::string
.
而且......下一步是什么?
邓诺?写代码?
#include <string>
#include <iostream>
void interlace(std::string &str, char ch)
{
for (std::size_t pos{ 1 }; pos < str.length(); pos += 2)
str.insert(pos, 1, ch);
}
int main()
{
std::string foo{ "string" };
interlace(foo, ''');
std::cout << foo << 'n';
}
输出:
s't'r'i'n'g
可能的优化:
正如 Remy Lebeau 所建议的那样,interlace()
可以确保它的参数str
在进入for
-循环之前保留了足够的内存,以避免循环中的重新分配:
void interlace(std::string &str, char ch)
{
auto length{ str.length() };
if (length < 2) // nothing to do
return;
str.reserve(2 * length - 1); // We insert a character after every character of str
// but the last one. eg. length == 3 -> 2 * 3 - 1
for (std::size_t pos{ 1 }; pos < str.length(); pos += 2)
str.insert(pos, 1, ch);
}
顺便说一句:
请注意:
<string>
,而不是<string.h>
。如果你*真的*想要来自C的字符串函数(std::strlen()
,std::strcpy()
,...),它们在C++<cstring>
。最好放弃
using namespace std;
的习惯,因为它会将std
中的所有标识符插入到全局命名空间中,这很容易导致标识符冲突。对于非常小的程序来说,这可能没有问题,但是......那:
char array[x.length()];
C++不合法。数组大小必须是编译时常量。您在此处使用的是
gcc
语言扩展。你不应该。这些东西被称为VLA(可变长度数组),这是C的一个特性。当您需要行为类似于数组但具有动态大小的东西时,请使用std::vector<>
。
相关文章:
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 使用动态分配将 char* 复制到另一个字符**
- 如何将一个结构的字符数组复制到结构的另一个字符数组中?
- 如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?
- 如何检查一个字符是否与字符数组中的另一个字符匹配?
- C++:使用另一个字符将一个字符大写
- 我可以得到一个字符 * 到一个 std::sregex_iterator 匹配 str() 吗?
- 使用连续分隔符和空最后一个字符进行拆分
- 如何比较文件中包含的下一个字符
- 如何检查字符串中的最后一个字符是否是某个字符并将其从字符串中删除?(C++)
- 如何从文本文件中一次读取一个字符
- 将一个字符替换为字符串中更多数量的字符,而不删除C++中的其他字母
- 读取输入后,输出丢失了一个字符
- 比较最后一个字符,不区分大小写(带谓词?
- 如果一个字符,比如说"9",我减去"0",我在结果上使用 is 数字,我是真还是假
- 为什么 std::istream::gcount 返回的字符比预期的多一个字符
- 使用 fstream 在空格分隔文件中查看下一项(不仅仅是一个字符)的方法
- 使用 char 将一个字符数组分配给另一个字符数组时出现奇怪的行为
- 在弦乐器中删除最后一个字符