如何在C中只打印一些字符?

时间:2017-07-27 09:47:20

标签: c

我有一个数组:

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

例如,如果我只想打印该字符串的前5个字符,我尝试了以下内容:

 var varIwanttoprint = 'data/rnase.mtz'

但它是打印整个字符串。为什么呢?

4 个答案:

答案 0 :(得分:3)

您可以使用%.*s,在使用printf时,需要打印预期字节的大小和指向char的指针。例如,

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

但它是打印整个字符串。为什么呢?

您正在使用%-5s,这意味着-左对齐该字段中的文字。

En passant,使用接受的答案就像代码片段一样无法实现输出,即使它可能看起来很骇人听闻。

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

答案 1 :(得分:2)

-对齐的printf格式化程序,而不是 precision

你想要的是用于精确度的.形成器:

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

这将打印arr的前5个元素。

如果您想了解有关printf格式的更多信息,请查看this link

答案 2 :(得分: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;
}

答案 3 :(得分:0)

你可以通过多种方式完成这项工作。使用循环,循环所需的次数,每次都取出字符,你可以在字符串后面向下走一个临时的nul-terminate,然后你可以简单地使用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 '

仔细看看,如果您有任何问题,请告诉我。