开发者

how to split string and store it different variable

I need h开发者_开发知识库elp as I am completely stuck here. Any idea for crictism will be very helpful.

I have string say " cat-dog-animal" and i want string like "dog-cat-animal"

I am slightly struck. I know in C i can use strtok , but that will break the string. I AM wondering how to store that string in above format.

Thanks


Treat the first 2/3 of the string as a ring buffer and rotate the characters in it.

  1. Find the index of the last dash
  2. Save char at index
  3. Move all preceding chars down one position
  4. Restore saved char in step 2 to front of string.
  5. Repeat steps 2 to 4 until the first dash is in the index position.

Granted it is not the most efficient solution, but it does work. I'd post some actual code, but this sounds like homework.


Edit

#include <string.h>
void function( char * s )
{
    int second_dash = ( strrchr(s, '-') - s );

    do
    {
       char t = s[second_dash];
       memmove( s + 1, s, second_dash);
       s[0] = t;
    }
    while ( s[second_dash] != '-' );
 }

If your string library doesn't have strrchr() or memmove() they can be easily replaced by loops.


You could use sscanf and then rebuild the string from the 3 scanned substrings.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜