is there a function in string.h for substrings on a an array of characters?
Printable View
is there a function in string.h for substrings on a an array of characters?
strstr() maybe?
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:
The output is: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;
}
Code:kleid@Shiva:~/Programming/Laboratory$ ./a.out
ello
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.
could you explain to me thw use of malloc in the post by Kleid-0?