问题
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 "hello"
, keeping in mind that the substring I want to print is variable length, not always 5 chars?
I know that I could use a for
loop and putchar
or that I could copy the array and then add a null-terminator but I'm wondering if there's a more elegant way?
回答1:
Try this:
int length = 5;
printf("%*.*s", length, length, "hello there");
回答2:
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.
回答3:
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
回答4:
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
来源:https://stackoverflow.com/questions/4841219/print-part-of-a-string-in-c