Print part of a string in C

后端 未结 4 1721
有刺的猬
有刺的猬 2020-12-15 07:52

Is there a way to only print part of a string?

For example, if I have

char *str = \"hello there\";

Is there a way to just print

相关标签:
4条回答
  • 2020-12-15 08:30

    printf and friends work well when that's all you want to do with the partial string, but for a more general solution:

    char *s2 = s + offset;
    char c = s2[length]; // Temporarily save character...
    s2[length] = '\0';   // ...that will be replaced by a NULL
    f(s2);  // Now do whatever you want with the temporarily truncated string
    s2[length] = c;      // Finally, restore the character that we had saved
    
    0 讨论(0)
  • 2020-12-15 08:36

    You can use strncpy to duplicate the part of your string you want to print, but you'd have to take care to add a null terminator, as strncpy won't do that if it doesn't encounter one in the source string. A better solution, as Jerry Coffin pointed out, is using the appropriate *printf function to write out or copy the substring you want.

    While strncpy can be dangerous in the hands of someone not used to it, it can be quicker in terms of execution time compared to a printf/sprintf/fprintf style solution, since there is none of the overhead of dealing with the formatting strings. My suggestion is to avoid strncpy if you can, but it's good to know about just in case.

    size_t len = 5;
    char sub[6];
    sub[5] = 0;
    strncpy(sub, str + 5, len); // char[] to copy to, char[] to copy from(plus offset
                                // to first character desired), length you want to copy
    
    0 讨论(0)
  • 2020-12-15 08:43

    This will work too:

    fwrite(str, 1, len, stdout);
    

    It will not have the overhead of parsing the format specifier. Obviously, to adjust the beginning of the substring, you can simply add the index to the pointer.

    0 讨论(0)
  • 2020-12-15 08:50

    Try this:

    int length = 5;
    printf("%*.*s", length, length, "hello there");
    
    0 讨论(0)
提交回复
热议问题