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.
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.
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).
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.
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.
printf("%.*s", len, str);
and also, there is no C string that is not NULL terminated.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With