formatting a string

This is a discussion on formatting a string within the C Programming forums, part of the General Programming Boards category; if i have a string, how can i get a substring from it and store it in a new variable? ...

  1. #1
    Registered User
    Join Date
    Sep 2002
    Posts
    3

    formatting a string

    if i have a string, how can i get a substring from it and store it in a new variable?

    eg

    char str[100]

    and i want substring1 from character 20~30 and substring2 35-41
    strncp can not specify the starting position, can not use strtok because there is no particular delimiter.
    is there a easy way to do it in C?

    please help me

  2. #2
    Registered User The Junglist's Avatar
    Join Date
    Nov 2002
    Posts
    42
    If you alway know the indexes of the substring that you want, then just write a function of your own. Here's a real sloppy way of doing it :
    Code:
    void function( char* buffer, int startIndex, int endIndex, char*  newBuffer)
    {
         int i;
    
         for( i = startIndex; i < endIndex; i++ )
         {
              newBuffer[ i - startIndex] = buffer[i];
         }
    }
    otherwise you could look up strstr()

  3. #3
    Registered User
    Join Date
    Sep 2002
    Posts
    3
    Originally posted by vVv
    Use strncpy() (string.h).

    Code:
    char buf[100] = { ... },
         sub1[16],
         sub2[8];
    strncpy( sub1, &buf[20], 10 );
    sub1[10] = 0;
    strncpy( sub2, &buf[35], 6 );
    sub2[6] = 0;
    ahhhhh.........i c ........thanks man

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Please check my C++
    By csonx_p in forum C++ Programming
    Replies: 263
    Last Post: 07-24-2008, 09:20 AM
  2. String Class
    By BKurosawa in forum C++ Programming
    Replies: 117
    Last Post: 08-09-2007, 01:02 AM
  3. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 02:23 PM
  4. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 01:45 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21