我有一个数组:如何仅打印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,''是一面旗帜......所以...... –