2017-04-11 130 views
-3

我想在字符串的開頭添加零。我正在使用格式說明符。 我的輸入字符串是「你好」 我想輸出爲「000hello」。C格式化的字符串 - 如何使用sprintf將前導零添加到字符串值?

我知道如何做到這一點整數。

int main() 
{ 
    int i=232; 
    char str[21]; 
    sprintf(str,"%08d",i); 

    printf("%s",str); 

    return 0; 
} 

輸出將是 - 00000232

如果我字符串做同樣的。

int main() 
    { 
     char i[]="hello"; 
     char str[21]; 
     sprintf(str,"%08s",i); 

     printf("%s",str); 

     return 0; 
    } 

輸出將是 - 個招呼(3前導空格)

爲什麼它是整數的情況下給予的字符串和零的情況下,空間?

+1

的printf( 「000000%S」,helloStr) – schil227

+0

我會做的是有一個數組,並且所有的元素設置爲 '0' ,除了空終止符的最後一個。然後在適當的地方複製你的字符串(提示:使用'strlen')並打印出來。或者,有一個循環打印出正確數量的'0',然後打印字符串。 – AntonH

+3

*我正在使用格式說明符。我的輸入字符串是「你好」*。請發佈顯示問題的[Minimal,Complete和Verifiable示例](http://stackoverflow.com/help/mcve)。在問題**中顯示輸入,預期輸出和實際輸出**。 –

回答

-1
void left_fill_zeros(char* dest, const char* str, int length) 
{ 
    sprintf(dest, "%.*d%s", (int)(length-strlen(str)), 0, str); 
} 

int main(void) 
{ 
    char output[256]; 
    left_fill_zeros(output, "Hello", 10); 
    puts(output); 

    // Total length will be 10 chars 
    // Output will be: "00000Hello" 
    return 0; 
} 
+0

嗯,在審查,我的答案只是有點不同,以應付小寬度,並做了一些錯誤檢查。太糟糕了這個答案的2 DV沒有包含一些細節,它的弱點。這當然至少是一個很好的起點。 – chux

-2

爲了解決您的具體問題 - 3個零點之前的 「hello」 - 然後執行:

#include <stdio.h> 

int main() 
    { 
     char i[] = "hello"; 
     printf("000%s",i); 

     return 0; 
    } 

結果:000hello

現在,如果你不具備多少個零的規範你需要填充不同長度的字符串,那麼下面的命令會在固定長度的字符串「hello」前加上3個零,使用sprintf()

#include <stdio.h> 

int main(void) { 
    char i[] = "hello"; 
    char buf[] = "000"; 
    char output[10]; 

    sprintf(output, "%s%s", buf,i); 
    printf("%s\n", output); 

    return 0; 
} 

結果:000hello

+0

我想用sprintf函數來做到這一點。 我可以放多少零。 – kid

+0

好吧,這是更清晰的事情。 – tale852150

+0

@kid - 此更新是否可解決您的問題? – tale852150

-1

如何使用sprintf的前導零添加到字符串值?

使用"%0*d%s"預先置零。

"%0*d" - 零>0分鐘寬度,從參數列表*衍生寬度,d打印一個int

字符串預先不需要零時,需要例外。

void PrependZeros(char *dest, const char *src, unsigned width) { 
    size_t len = strlen(src); 
    if (len >= width) strcpy(dest, src); 
    else sprintf(dest, "%0*d%s", (int) (width - len), 0, src); 
} 

然而,我不認爲sprintf()是這個職位的合適的工具,並會爲下面的代碼。

void PrependZeros(char *dest, const char *src, unsigned width) { 
    size_t len = strlen(src); 
    size_t zeros = (len > width) ? 0 : width - len; 
    memset(dest, '0', zeros); 
    strcpy(dest + zeros, src); 
} 

void testw(const char *src, unsigned width) { 
    char dest[100]; 
    PrependZeros(dest, src, width); 
    printf("%u <%s>\n", width, dest); 
} 

int main() { 
    for (unsigned w = 0; w < 10; w++) 
    testw("Hello", w); 
    for (unsigned w = 0; w < 2; w++) 
    testw("", w); 
} 

輸出

0 <Hello> 
1 <Hello> 
2 <Hello> 
3 <Hello> 
4 <Hello> 
5 <Hello> 
6 <0Hello> 
7 <00Hello> 
8 <000Hello> 
9 <0000Hello> 
0 <> 
1 <0>