Print part of a string in C

后端 未结 4 1736
有刺的猬
有刺的猬 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: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
    

提交回复
热议问题