character substring

This is a discussion on character substring within the C++ Programming forums, part of the General Programming Boards category; Ok... I know how to get a substring using the variable type "string," BUT... how do I get a substring ...

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

    character substring

    Ok... I know how to get a substring using the variable type "string," BUT... how do I get a substring of an array of characters.

    For instance, if I have a character array of size 9, how do I pull out the first 4 characters?

    I've tried:
    Code:
    char temp1[9] = "temporary";
    char temp2[4];
    
       strcpy (temp2 , temp1);
    but that just resizes the size of "temp2" instead of filling up the array with as many characters as it can and then stopping. "strcat" didn't work either! I just need the first 4 characters assigned to their own variable. I'm only asking the user for input once. I know its probably something simple. Please help if you can... thanks!

  2. #2
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,600
    strncpy copys up to N chars. Still you should null terminate manually...

    Code:
     char str[100] = "temporary";
    
     char sub[100];
    
     strncpy(sub, str, 4);
    
     sub[4] = 0;
    
     printf("Sub: %s", sub);
    
     //...now try from the middle...
    
     char * found = strstr(str, "mp");
    
      if(found){
       strncpy(sub, found, 4);
       sub[4] = 0;
       printf("Sub: %s", sub);
       }
    Code:
    if( numeric_limits< byte >::digits != bits_per_byte )
        error( "program requires bits_per_byte-bit bytes" );
    24bbs.cpp

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

    THANK YOU

    I saw that function and didn't look twice at it. Thank you so much!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 11
    Last Post: 10-07-2008, 06:19 PM
  2. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 01:53 AM
  3. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM
  4. UNICODE and GET_STATE
    By Registered in forum C++ Programming
    Replies: 1
    Last Post: 07-15-2002, 03:23 PM
  5. character substring
    By ghe1 in forum C++ Programming
    Replies: 3
    Last Post: 02-19-2002, 10:34 AM

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