简体   繁体   中英

Print only the rightmost part of a string

I am applying printf and/or other functions to a certain string of characters, read from a file. I want to skip the first 5 characters under certain conditions. Now I thought to be clever by, if the conditions apply, increasing the string pointer by 5:

 if (strlen(nav_code) == 10 ) {nav_code = 5+nav_code;}

but the compiler refuses this:

error: assignment to expression with array type

What have I misunderstood? How to make my idea work - or is it a bad idea anyway?

It's probably becuase nav_code is not a pointer but a character array like char nav_code[50] . Try the following:

char nav_code[50];
char *nav_code_ptr = nav_code;
if (strlen(nav_code_ptr) == 10 ) {nav_code_ptr += 5;}
// forth on, use nav_code_ptr instead of nav_code

I am applying printf and/or other functions to a certain string of characters, read from a file. I want to skip the first 5 characters under certain conditions.

If printf is all what you need, then sure you can skip the first 5 characters.

Given nav_code is string (either char array or char pointer), then:

printf( "%s", nav_code + 5 );  // skip the first 5 characters

Of course you need to make sure your string has more than 5 characters, otherwise it's flat out illegal as out-of-bound access.

In your code, nav_code is an array and arrays cannot be assigned .

Instead, use a pointer, initialize that with the address of the first element of the array, make pointer arithmetic on that pointer and store the updated result back to the pointer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM