Thread: c strings

  1. #1
    Registered User
    Join Date
    Nov 2004
    Posts
    86

    c strings

    is there a function in string.h for substrings on a an array of characters?

  2. #2
    Registered User
    Join Date
    Sep 2004
    Posts
    719
    strstr() maybe?
    i seem to have GCC 3.3.4
    But how do i start it?
    I dont have a menu for it or anything.

  3. #3
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    You may want to try looking at this:
    C String Functions
    I cooked this up real quick, I'm not totally sure if this is what you wanted though:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    char *getSubstring(char *haystack, int start, int end);
    
    int main(void) {
     char *myString = "Hello World";
     char *mySubString = NULL;
    
     if( (mySubString = getSubstring(myString, 1, 4)) == NULL) {
      puts("Substring error");
      return 0;
     }
    
     puts(mySubString);
     return 0;
    }
    
    char *getSubstring(char *haystack, int start, int end) {
     char *substring = malloc(255 * sizeof(*substring));
    
     if(end < start)
      return NULL;
    
     int i, location=0;
     for(i=start; i<=end; ++i) {
      if(haystack[i] == '\0') return NULL;
    
      substring[location++] = haystack[i];
     }
     substring[location] = '\0';
     return substring;
    }
    The output is:
    Code:
    kleid@Shiva:~/Programming/Laboratory$ ./a.out
    ello

  4. #4
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    You may need to be more specific, but it sounds to me like you want to tokenize a string. If you have a string containing several substrings, separated by a certain character, strtok will replace that character with a null character, and return a pointer to the beginning of that 'token'. You do this a couple of times, and you've "tokenized" a string.

  5. #5
    Registered User
    Join Date
    Nov 2004
    Posts
    86
    could you explain to me thw use of malloc in the post by Kleid-0?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Strings Program
    By limergal in forum C++ Programming
    Replies: 4
    Last Post: 12-02-2006, 03:24 PM
  2. Programming using strings
    By jlu0418 in forum C++ Programming
    Replies: 5
    Last Post: 11-26-2006, 08:07 PM
  3. Reading strings input by the user...
    By Cmuppet in forum C Programming
    Replies: 13
    Last Post: 07-21-2004, 06:37 AM
  4. damn strings
    By jmzl666 in forum C Programming
    Replies: 10
    Last Post: 06-24-2002, 02:09 AM
  5. menus and strings
    By garycastillo in forum C Programming
    Replies: 3
    Last Post: 04-29-2002, 11:23 AM