如何将字符串与一个字符交错?

How to interlace string with one character?

本文关键字:一个 字符 字符串      更新时间:2023-10-16

我需要编写一个函数,例如用"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<>

相关文章: