2017-07-27 27 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字节':)' –