Reputation: 16081
In C, how do I extract the first n characters from a string until I find a space in the string? Essentially, which C function will find the position of the next space for me and which C function will give me a substring? I am thinking in terms of C++. such as:
string str = "Help me Please!";
int blankPos = str.find(' ');
str.substr(0, blankPos);
Thanks,
Upvotes: 1
Views: 6293
Reputation: 490
char str[] = "Help me Please"; // Source string
char newstr[80]; // Result string
// Copy substring characters until you reach ' ' (i.e. "Help")
for (i=0; str[i] != ' '; i++) {
newstr[i] = str[i];
}
newstr[i] = 0; // Add string terminator at the end of substring
Upvotes: 1
Reputation: 11871
Another variant allowing to use more than one character as delimitter.
char str[] = "Help me Please";
char newstr[80];
char *p = strpbrk(str, " \t\xA0"); /* space, tab or non-breaking space (assuming western encoding, that part would need adaptation to be trule portable) */
if(p)
strlcpy(newstr, str, p - str + 1);
else
newstr[0] = 0;
strlcpy
is not standard but widespread enough to be used. If it is not available on the platform, it's easy to implement. Note that strlcpy
always puts a 0 at the last position copied, therfore the +1 in the length expression.
Upvotes: 0
Reputation: 3500
char* str = "Help me Please";
int i =0;
//Find first space
while(str[i] != ' '){
i++;
}
char* newstr;
newstr = strndup(str+0,i);
I guess you could also use strchr() to get the first space in the string.
Upvotes: 0
Reputation: 45968
So you want something like:
#include <string.h>
const char *str = "Help me Please";
//find space charachter or end of string if no space found
char *substr, *space = strchr(str, ' ');
int len = space ? (space-str) : strlen(str);
//create new string and copy data
substr = malloc(len+1);
memcpy(substr, str, len);
substr[len] = 0;
Upvotes: 0
Reputation: 3070
If you just want to get the first part of the string, use strchr()
as everyone has suggested. If you're looking to break a string into substrings delimited by spaces, then look into strtok()
.
Upvotes: 0
Reputation: 363858
strchr
to find the space.char
buffer to hold the substring.memcpy
.Upvotes: 1