【发布时间】:2014-05-11 12:20:49
【问题描述】:
我有一个字符数组,我想从固定位置开始移动它的某些位置,并为移动的位置数量放置空格。
例如,如果我有数组:
(read A var := 5)
如果我想将它从第一个位置移动一个位置,我想得到:
( read A var := 5)
但是我得到了:
((ead A var := 5)
你可以在下面找到我的源代码:
#include <iostream>
#include <cctype>
#include <cstdio>
#include <cstring>
using namespace std;
char output[100] = "(read A var := 5)";
void move(int spos, int places)
{
int i = places, j = spos;
for (int k = 0; k < places; k++) {
output[j+i] = output[j];
i++;
j++;
}
}
int main(void)
{
for (i = 0; i < strlen(output); i++)
cout << output[i];
cout << endl;
move(0, 1);
output[18] = '\0';
for (i = 0; i < strlen(output); i++)
cout << output[i];
cout << endl;
return 0;
}
【问题讨论】:
-
如果您使用 C++,为什么不使用
std::string? -
更改
move循环以向后工作。 (或者使用memmove,它可以正确处理重叠的源和目标。) -
@OliCharlesworth 因为我需要使用字符。
-
@Jongware 你的意思是 memmove(output+1, output+1, 1); ?虽然它产生相同的字符串而没有任何变化。
-
类似的东西,是的。
memmove采用 destination、source、length 参数。试试memmove (output+places, output+spos, strlen(output+spos)+1);-- 凭记忆,未经测试。