How to get string from front of array to position x?

A

Angus

Hi

If I want to eg print a string from position 3 to the end of the
string I can do this:
char szMessage[] = "Hello World";
printf("string fragment: %s\n", szMessage+5);

But if I just want to print "Hello" how can I do it. I can make a
copy but what other way to do this?

Angus
 
W

Willem

Angus wrote:
) If I want to eg print a string from position 3 to the end of the
) string I can do this:
) char szMessage[] = "Hello World";
) printf("string fragment: %s\n", szMessage+5);
)
) But if I just want to print "Hello" how can I do it. I can make a
) copy but what other way to do this?

The width/precision specifiers for the printf formats work on strings
as well. (Note that there are two specifiers, separated by a dot.)
As a bonus, you can use * for a specifier, and then give the value
in the argument list.


SaSW, Willem
--
Disclaimer: I am in no way responsible for any of the statements
made in the above text. For all I know I might be
drugged or something..
No I'm not paranoid. You all think I'm paranoid, don't you !
#EOT
 
E

Eric Sosman

Hi

If I want to eg print a string from position 3 to the end of the
string I can do this:
char szMessage[] = "Hello World";
printf("string fragment: %s\n", szMessage+5);

That would print from position 5 (the ' ') onward, not position 3.
But if I just want to print "Hello" how can I do it. I can make a
copy but what other way to do this?

One way is to use the "precision" modifier in the format:

printf ("string fragment: %.5s\n", szMessage);

The ".5" instructs printf() to print no more than 5 characters,
even if the argument string is longer. (If it's shorter, printf()
will print the entire string.)
 
L

lawrence.jones

Angus said:
If I want to eg print a string from position 3 to the end of the
string I can do this:
char szMessage[] = "Hello World";
printf("string fragment: %s\n", szMessage+5);

Actually, that's position 5 (or 6, depending on how you count).
But if I just want to print "Hello" how can I do it. I can make a
copy but what other way to do this?

printf("string fragment: %.5s\n", szMessage);

Don't you have a reference that includes printf format specifiers?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top