我有一個數組:如何僅打印C中的一些字符?
char arr[]="This is the string";
舉例來說,如果我想打印該字符串的只有前5個字符,我曾嘗試以下:
printf("%-5s",arr);
但它打印整個字符串。爲什麼?
我有一個數組:如何僅打印C中的一些字符?
char arr[]="This is the string";
舉例來說,如果我想打印該字符串的只有前5個字符,我曾嘗試以下:
printf("%-5s",arr);
但它打印整個字符串。爲什麼?
-
爲理由,不精度一個printf格式化器。
你想要什麼.
格式化器被用於精密:
printf("%.5s", arr);
這將打印的arr
第5個元素。
如果您想了解更多關於printf formaters的內容,請看this link。
您可以使用%.*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
例如串提取功能(子提取到的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;
}
您可以通過多種方式做到這一點很簡單。使用一個循環,循環所需的次數,每次拾取字符,您可以在第五個字符之後將指針向下移動一個臨時終止符,或者您可以簡單地使用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 '
看東西了,讓我知道,如果你有任何問題。
額外的內存消費者:) – snr
是 - 內存豬(全部13字節':)' –
'「%-5s」'只是一個字符串格式化程序。它不會截斷字符串。 –
使用精度。 Google的printf精度。 –
@xing你確定''.'語法嗎? AFAIR,''是一面旗幟......所以...... –