在字符串中间添加字符

时间:2013-07-16 02:24:48

标签: c

因为血腥的年代而被困在这上面。似乎没有简单的方法来做到这一点!

请一些帮助,谢谢!

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

char (char *s, const int len) {
{
   static const char alphanum[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                                  "123456789";
   for (int i = 0; i < len; ++i) {
        s[i] = alphanum[(sizeof(alphanum) - 6)];
    }

    s[len] = 0;
    memmove(s+pos+1, s+pos, len-pos+1);
    s[pos]='-';
    puts(s);
}

int main (void)
{
//print the random digits but in the middle need to insert - e.g
//FJ3-FKE
}

2 个答案:

答案 0 :(得分:3)

有两种简单的方法。

如果您只需要打印那些东西,您可以在输出中添加短划线,如下所示:

fwrite(s, pos, stdout);
putchar('-');
puts(s+pos);

或者,如果用于s的缓冲区大到足以容纳一个char,则可以使用memmove为短划线留出空间,添加短划线和然后打印字符串:

memmove(s+pos+1, s+pos, len-pos+1);
s[pos]='-';
puts(s);

(所有这些都假设pos是插入破折号的位置)

答案 1 :(得分:0)

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

void func(char *s, int len, int pos) {
    static const char alphanum[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                                   "123456789";
    for (int i = 0; i < len; ++i) {
        s[i] = alphanum[rand()%(sizeof(alphanum)-1)];
    }
    s[len] = 0;

    if(0 < pos && pos < len){
        memmove(s+pos+1, s+pos, len-pos+1);
        s[pos]='-';
    }
}

int main (void){
    char s[10];
    srand(time(NULL));
//print the random digits but in the middle need to insert - e.g
//FJ3-FKE
    func(s, 6, 3);
    puts(s);
    return 0;
}
相关问题