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

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

问题描述

我也充满了一些字符一个字符数组。比方说,我有的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)
);

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

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