Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C语言字符数组 #14

Open
tiodot opened this issue May 26, 2017 · 0 comments
Open

C语言字符数组 #14

tiodot opened this issue May 26, 2017 · 0 comments

Comments

@tiodot
Copy link
Owner

tiodot commented May 26, 2017

问题1:添加字符到字符数组头部

问题描述:因为C语言中不能使用+来拼接字符串,那如何向字符数组开头添加字符?
解决方案:使用memmove方式,将字符数组中已有数据往后一个位置。

#include <stdio.h>
#include <string.h>

char s[32];
s[0] = 'a';
memmove(s + 1, s, strlen(s) + 1);
s[0] = 'b';
printf("s is: %s\n", s); // 输出ba

memmove相关介绍 C library function - memmove()。如果需要添加字符串到头部,可以封装一个函数:

/* Prepends t into s. Assumes s has enough space allocated
** for the combined string.
*/
void prepend(char* s, const char* t)
{
    size_t len = strlen(t);
    size_t i;

    memmove(s + len, s, strlen(s) + 1);

    for (i = 0; i < len; ++i)
    {
        s[i] = t[i];
    }
}

参考:Prepending to a string

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant