如何从一个句子高效地使用C提取的话呢? [英] How to extract words from a sentence efficiently in C?

查看:85
本文介绍了如何从一个句子高效地使用C提取的话呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要提取第一,第二和休息的句子分成三个变量的一个有效的功能。

I need an efficient function that extracts first second and rest of the sentence into three variables.

推荐答案

简单的方法:使用的strtok()或strtok_r率先拿到两个标记,这将在字符串中删除他们,所以字符串本身将是你的,你正在寻找第三个令牌。

Easy way: Use strtok() or strtok_r to get the first two tokens, which will remove them from the string, so the string itself will be your third token you were looking for.

硬办法:自己解析:(

strtok的是在C字符串库,并会产生变异的原始字符串,所以要小心,先复制的字符串,如果它需要保持不变。

Strtok is in the C string library, and will mutate your original string so be careful, copy the string first if it needs to remain intact.

可能的例子:

//#include <string.h>

char input[] ="first second third forth";
char delimiter[] = " ";
char *firstWord, *secondWord, *remainder, *context;

int inputLength = strlen(input);
char *inputCopy = (char*) calloc(inputLength + 1, sizeof(char));
strncpy(inputCopy, input, inputLength);

firstWord = strtok_r (inputCopy, delimiter, &context);
secondWord = strtok_r (NULL, delimiter, &context);
remainder = context;

printf("%s\n", firstWord);
printf("%s\n", secondWord);
printf("%s\n", remainder);

getchar();
free(inputCopy);

这应该只是罚款,并与线程原始字符串未突变。

This should work just fine and be threadsafe with the original string unmutated.

这篇关于如何从一个句子高效地使用C提取的话呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆