Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print string first n bytes when the string's length is greater than n?

So I have a string that has a certain amount of bytes (or length). I say bytes because there is no NULL terminator at the end of the string. Though, I know how long the string is. Normally, as we all know, when you printf("%s", str);, it will keep printing every byte until it gets to a NULL character. I know there is no C string that is not NULL terminated, but I have a weird situation where I'm storing stuff (Not specifically strings) and I don't store the NULL, but the length of the "thing".

Here is a little sample:

char* str = "Hello_World"; //Let's use our imagination and pretend this doesn't have a NULL terminator after the 'd' in World
long len = 5;

//Print the first 'len' bytes (or char's) of 'str'

I know you are allowed to do something like this:

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

But with that situation, I'm hard coding the 5 in, though with my situation, the 5 is in a variable. I would do something like this:

printf("%.(%l)s", len, str);

But I know you can't do that. But gives you an idea of what I'm trying to accomplish.

like image 283
Rob Avery IV Avatar asked Mar 13 '13 03:03

Rob Avery IV


People also ask

How do you calculate string size in bytes?

So a string size is 18 + (2 * number of characters) bytes. (In reality, another 2 bytes is sometimes used for packing to ensure 32-bit alignment, but I'll ignore that). 2 bytes is needed for each character, since . NET strings are UTF-16.

Can you use the precision specifier to limit the number of characters printed from a string?

I learned recently that you can control the number of characters that printf will show for a string using a precision specifier (assuming your printf implementation supports this). Note the . 5 that is included in the %s symbol: that tells printf to print a maximum of five characters ( NULL termination is still valid).

How do I print part of a string?

printf("%. *s", length, "hello there") will do the trick as well -- the first * just means that a sub- length string will be padded to length characters, which may or may not be the desired behavior.

Is string length equal to bytes?

Nope. A zero terminated string has one extra byte. A pascal string (the Delphi shortstring) has an extra byte for the length. And unicode strings has more than one byte per character.


2 Answers

printf("%.*s", len, str);

and also, there is no C string that is not NULL terminated.

like image 114
Aniket Inge Avatar answered Oct 20 '22 03:10

Aniket Inge


You can do this:

for (int i =0; i<len; i++)
{
    printf("%c", str[i]);
}

Which will print them in the same line, looping for whatever lenght you need to print.

like image 25
RobertoNovelo Avatar answered Oct 20 '22 03:10

RobertoNovelo