2017-07-27 49 views
2

我有一個數組:如何僅打印C中的一些字符?

char arr[]="This is the string"; 

舉例來說,如果我想打印該字符串的只有前5個字符,我曾嘗試以下:

printf("%-5s",arr); 

但它打印整個字符串。爲什麼?

+1

'「%-5s」'只是一個字符串格式化程序。它不會截斷字符串。 –

+1

使用精度。 Google的printf精度。 –

+1

@xing你確定''.'語法嗎? AFAIR,''是一面旗幟......所以...... –

回答

3

-理由,不精度一個printf格式化器。

你想要什麼.格式化器被用於精密:

printf("%.5s", arr); 

這將打印的arr第5個元素。

如果您想了解更多關於printf formaters的內容,請看this link

4

您可以使用%.*s,它與printf一起使用時,需要打印預期字節的大小以及指向char的指針作爲參數。例如,

// It prints This 
printf("%.*s", 4, arr); 

但它打印整個字符串。爲什麼?

您正在使用%-5s表示-左對齊您在該字段中的文本。


順便,輸出不能使用公認的答案一樣簡單的代碼片段,即使它可能會嘲笑似乎實現。

int i; 
char arr[]="This is the string"; 

for (i = 1; i < sizeof(arr); ++i) { 
    printf("%.*s\n", i, arr); 
} 

輸出:

T 
Th 
Thi 
This 
This 
This i 
This is 
This is 
This is t 
This is th 
This is the 
This is the 
This is the s 
This is the st 
This is the str 
This is the stri 
This is the strin 
This is the string 
+0

真的很高興使用'*'來允許動態選擇要顯示的字符數 – Garf365

+0

是的,使用引號間的精度有時並不好,因爲如果我想要在'for循環中'或通過宏定義##定義....'就像那個@ Garf365 – snr

0

例如串提取功能(子提取到的buff)

char *strpart(char *str, char *buff, int start, int end) 
{ 
    int len = str != NULL ? strlen(str) : -1 ; 
    char *ptr = buff; 

    if (start > end || end > len - 1 || len == -1 || buff == NULL) return NULL; 

    for (int index = start; index <= end; index++) 
    { 
     *ptr++ = *(str + index); 
    } 
    *ptr = '\0'; 
    return buff; 
} 
+1

我覺得這個解決方案不是在這種情況下需要的 – horro

+0

@horro爲什麼?他希望打印**作爲標題狀態的一部分**字符串。 –

+1

工程師誰使用最低庫存來製造最好的東西。 – snr

0

您可以通過多種方式做到這一點很簡單。使用一個循環,循環所需的次數,每次拾取字符,您可以在第五個字符之後將指針向下移動一個臨時終止符,或者您可以簡單地使用strncpy將5個字符複製到緩衝區並打印那。 (這可能是最簡單的),例如

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

int main (void) 
{ 
    char arr[]="This is the string", 
     buf[sizeof arr] = "";  /* note: nul-termination via initialization */ 

    strncpy (buf, arr, 5); 

    printf ("'%s'\n", buf); 

    return 0; 
} 

示例使用/輸出

$ ./bin/strncpy 
'This ' 

看東西了,讓我知道,如果你有任何問題。

+2

額外的內存消費者:) – snr

+0

是 - 內存豬(全部13字節':)' –