2013-07-16 213 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; 
}