简体   繁体   English

如何在C中的数组中替换特定但不断变化的一系列字符?

[英]How to replace a specific but changing series of characters in an array in C?

I am working on 2 different programs, but have the same problem for both.我正在开发 2 个不同的程序,但两者都有相同的问题。 I have a char array (that doesn't hold meaningful text) that I use for drawing things on the screen.我有一个用于在屏幕上绘制内容的char数组(不包含有意义的文本)。 The first one is for a race line that shows progress, and the other one for the map of an area that can be modified.第一个用于显示进度的比赛线,另一个用于可以修改的区域地图。
What I want to do is overwrite a section of the array, not the entire array, without changing the array's size.我想要做的是覆盖数组,而不是整个阵列的部分,在不改变数组的大小。 For example, if array1 looks like |..........|例如,如果array1看起来像|..........| and I wanted to add a fallen tree at position 3 and a rock at position 10 it would change to |..-->>>..@|我想在位置 3 添加一棵倒下的树,在位置 10 添加一块岩石,它会变成|..-->>>..@| . . What I meant in my title for 'specific' is that the amount of characters to be replaced is given by me or determined during execution, instead of calling a function that automatically knows when to stop.我在标题中的“特定”的意思是,要替换的字符数量由我给定或在执行期间确定,而不是调用一个自动知道何时停止的函数。
I thought of doing it with a for loop, like:我想用for循环来做,比如:

char tree[5] = "-->>>";
char map[12] = "|..........|";
int offset = 3; //position from which to start replacing characters
object_size = sizeof(tree) / sizeof(char); //to get the length of the object to be added
for (int i = 0; i < object_size; i++) {
    map[offset + i] = tree[i];
}  

Is there a cleaner way to do it?有没有更干净的方法来做到这一点? I'm sure there must already be a function that does it, but most of what I find is in other languages.我确信肯定已经有一个函数可以做到这一点,但我发现的大部分内容都是用其他语言编写的。 The idea is to then be able to use a 2-dimensional array to store the map and modify bigger areas.这个想法是然后能够使用二维数组来存储地图并修改更大的区域。

If I have correctly understood, you do not want to copy the terminating null.如果我理解正确,您不想复制终止空值。 The standard library function to use is void *memcpy(void *dest, void *src, size_t size) that copies exactly size bytes from src to dest .要使用的标准库函数是void *memcpy(void *dest, void *src, size_t size) ,它将size字节从src精确复制到dest

But you have to ensure that there is enough room at dest to accept the size bytes但是必须确保 dest 有足够的空间来接受 size 字节

You can take a look at你可以看看

https://www.tutorialspoint.com/c_standard_library/string_h.htm https://www.tutorialspoint.com/c_standard_library/string_h.htm

And for you,以及对于你,

char *strcpy(char *dest, const char *src)

char *strncpy(char *dest, const char *src, size_t n)

They can make your code cleaner, but i think that deep inside, they do what you're doing manually.他们可以让你的代码更干净,但我认为在内心深处,他们做你手动做的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM