-
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!
-
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);
}
-
THANK YOU
I saw that function and didn't look twice at it. Thank you so much!