在 char 数组中间插入字符 [英] Inserting characters in the middle of char array

查看:21
本文介绍了在 char 数组中间插入字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 char 数组,里面填充了一些字符.假设我的 char 数组中有HelloWorld".(不是字符串.占用 0 到 9 的索引)

I have a char array filled with some characters. Let's say I have "HelloWorld" in my char array. (not string. taking up index of 0 to 9)

我要做的是在数组中间插入一个字符,然后将其余的推到一边,以便为插入的新字符腾出空间.

What I'm trying to do is insert a character in the middle of the array, and push the rest to the side to make room for the new character that is being inserted.

所以,我可以让 char 数组中包含Hello.World".

So, I can make the char array to have "Hello.World" in it.

char ch[15]; // assume it has "HelloWorld" in it
for(int i=0; i<=strlen(ch)-1; i++) {
    if(ch[i]=='o' && ch[i+1]=='W') {
        for(int j=strlen(ch)-1; j>=i+2; j--) {
            ch[j] = ch[j-1]; // pushing process?
        }
        ch[i+1] = '.';
        break;
    }
}

这行得通吗?会有更简单的方法吗?我可能只是想得太复杂了.

Would this work? Would there be an easier way? I might just be thinking way too complicated on this.

推荐答案

如果你想将所有字符向上移动一个,那么你可以使用 memmove 来实现.

If you want to move all the characters up by one, then you could do it using memmove.

#include <string.h>

char ch[15];

int make_room_at = 5;
int room_to_make = 1;

memmove(
    ch + make_room_at + room_to_make,
    ch + make_room_at,
    15 - (make_room_at + room_to_make)
);

这篇关于在 char 数组中间插入字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆