2013-07-16 201 views
1

在血腥时代,我一直坚持这一点。似乎没有简单的方法来做到这一点!在字符串中间添加字符

会提供一些帮助,谢谢!

#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 
} 
+0

;'... –

+0

哦,对了,是没有意识到笑 –

+0

请分享你已经试过的东西 – RGG

回答

2

有两种简单的方法。

如果你只需要打印的东西,你可以添加几许只是在输出中,像这样的:

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就是插入仪表板的位置),我想你的意思是`S [LEN] = 0

+0

嗯,我真的需要把它放在一个字符串中,因为我将在Web请求中使用它。无论如何要做到这一点? –

+0

@ragingfire:它已经在那里,在第二个解决方案... –

+0

好的更新的代码将在6位数的确切中间? –

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; 
}