在C中,如何从字符串中提取前n个字符,直到我在字符串中找到空格?基本上,哪个C函数会为我找到下一个空格的位置,哪个C函数会给我一个子串?我在思考C ++。如:
string str = "Help me Please!";
int blankPos = str.find(' ');
str.substr(0, blankPos);
谢谢,
答案 0 :(得分:1)
提示:strchr()
我需要输入更多字符。
答案 1 :(得分:1)
strchr
查找空格。char
缓冲区来保存子字符串。memcpy
将子字符串复制到缓冲区。答案 2 :(得分:1)
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
答案 3 :(得分:0)
char* str = "Help me Please";
int i =0;
//Find first space
while(str[i] != ' '){
i++;
}
char* newstr;
newstr = strndup(str+0,i);
我猜你也可以使用strchr()获取字符串中的第一个空格。
答案 4 :(得分:0)
所以你想要这样的东西:
#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;
答案 5 :(得分:0)
如果您只想获取字符串的第一部分,请按照每个人的建议使用strchr()
。如果您希望将字符串分解为由空格分隔的子字符串,请查看strtok()
。
答案 6 :(得分:0)
允许使用多个字符作为分隔符的另一种变体。
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
不是标准的,但足以广泛使用。如果它在平台上不可用,则很容易实现。请注意,strlcpy
始终在复制的最后位置放置0,因此在长度表达式中为+1。