Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print part of a string in C

Tags:

c

c-strings

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?

like image 731
Mark Avatar asked Jan 30 '11 04:01

Mark


People also ask

How do you print only part of a string in C?

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.

How does %s work in C?

%c deals with a char (that is, a single character), whereas %s deals with a char * (that is, a pointer to an array of characters, hopefully null-terminated).

What is %s in printf in C?

%s tells printf that the corresponding argument is to be treated as a string (in C terms, a 0-terminated sequence of char ); the type of the corresponding argument must be char * . %d tells printf that the corresponding argument is to be treated as an integer value; the type of the corresponding argument must be int .

Is there a substring function in C?

So it turns out that, in C, it's actually impossible to write a proper "utility" substring function, that doesn't do any dynamic memory allocation, and that doesn't modify the original string. All of this is a consequence of the fact that C does not have a first-class string type.


2 Answers

Try this:

int length = 5;
printf("%*.*s", length, length, "hello there");
like image 169
Jerry Coffin Avatar answered Oct 05 '22 06:10

Jerry Coffin


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.

like image 37
mmx Avatar answered Oct 05 '22 08:10

mmx