c++ - 将符号插入字符串 C++

标签 c++ string

我需要在字符串的每五个符号后插入符号“+”。 st - 字符串类型的 String 类的成员

int i = 1;
int original_size = st.size;

int count = 0;
int j;
for (j = 0; j < st.size; j++)
{
    if (i % 5)
        count++;
}

while (st.size < original_size + count)
{
    if (i % 5)
    {   
        st.insert(i + 1, 1, '+');
        st.size++;
    }
    i++;
}

return st;

我在这部分代码中遇到错误。我认为这与 while-cycle 的条件有关。你能帮我怎么做吗?

最佳答案

如果我没听错,那么您希望在原始字符串中每 5 个字符插入一个“+”字符。一种方法是创建一个临时字符串,然后重新分配原始字符串:

std::string st("A test string with some chars");
std::string temp;

for (int i = 1; i <= st.size(); ++i)
{
    temp += st[i - 1];
    if (i % 5 == 0)
    {
        temp += '+';
    }
}
st = temp;

您会注意到我从 1 开始循环,这是为了避免在第一次迭代时插入“+”(0%5==0)。

关于c++ - 将符号插入字符串 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32482950/

相关文章:

string - 多个 StringProperty 的 Javafx 串联

string - 寻找最小泛语法窗口的有效算法?

c++ - 使用 glDrawPixels 时遇到问题

c++ - (Visual) C++ 的数据库抽象层

python - Python 中的字符串等价/比较

C 连接字符串不起作用

c++ - 使用 AVX 异或两个 zmm(512 位)寄存器

c++ - 使用内存映射技术的日志记录机制

c++ - 为什么我得到 "error: ‘apply’ is not member of ‘std’”?

string - 将字符串a转换为字符串b