问题描述
我试图分割线成词的数组,但我被困在如何做到这一点的C.我用C技能不是很好,所以我不能想办法执行我的想法。她是我迄今为止:
INT beginIndex = 0;
INT endIndex的= 0;
INT maxWords = 10;
而(1){
而(!isspace为(STR)){
endIndex的++;
}
字符* TMP =(String一个从beginIndexSTR到endIndex)
ARR [wordCnt] = tmp目录;
wordCnt ++;
beginIndex = endIndex的;
如果(wordCnt = maxWords){
返回;
}
}
在我的方法,我收到(的char * str中,字符* ARR [10]),和STR是,我想,当我遇到一个空间分割线。 ARR是我要存储字阵列。有什么办法字符串的'块',我是从'海峡'想复制到我的TMP变量?这是我现在能想到的最好的办法,也许这是一个可怕的想法。如果是这样,我会很乐意得到一些文件或提示上更好的方法。
的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&string.h中GT;
#包括LT&;&文件ctype.h GT;INT拆分(的char * str中,字符* ARR [10]){
INT beginIndex = 0;
INT endIndex的;
INT maxWords = 10;
INT wordCnt = 0; 而(1){
而(isspace为(STR [beginIndex])){
++ beginIndex;
}
如果(STR [beginIndex] =='\\ 0')
打破;
endIndex的= beginIndex;
而(STR [endIndex的&放大器;&安培;!isspace为(STR [endIndex的])){
++ endIndex的;
}
INT LEN = endIndex的 - beginIndex;
字符* TMP =释放calloc(LEN + 1的sizeof(字符));
的memcpy(TMP,&安培; STR [beginIndex],LEN);
ARR [wordCnt ++] = tmp目录;
beginIndex = endIndex的;
如果(wordCnt == maxWords)
打破;
}
返回wordCnt;
}诠释主要(无效){
字符* ARR [10];
INT I;
INT N =拆分(第一第二第三,ARR); 对于(i = 0; I< N ++我){
看跌期权(ARR [I]);
免费(ARR [I]);
} 返回0;
}
I am trying to split a line into an array of words, but I am stuck on how to do this in C. My skills in C aren't very good, so I can't think of a way to "execute" my idea. Her is what I have so far:
int beginIndex = 0;
int endIndex = 0;
int maxWords = 10;
while (1) {
while (!isspace(str)) {
endIndex++;
}
char *tmp = (string from 'str' from beginIndex to endIndex)
arr[wordCnt] = tmp;
wordCnt++;
beginIndex = endIndex;
if (wordCnt = maxWords) {
return;
}
}
In my method I receive (char *str, char *arr[10]), and str is the line that I want to split when I encounter a space. arr is the array where I want to store the words. Is there any way to copy the 'chunk' of string that I want from 'str' into my tmp variable? This is the best way that I can think of right now, perhaps it's a terrible idea. If so, I would be happy to get some documentation or tips on a better method.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int split(char *str, char *arr[10]){
int beginIndex = 0;
int endIndex;
int maxWords = 10;
int wordCnt = 0;
while(1){
while(isspace(str[beginIndex])){
++beginIndex;
}
if(str[beginIndex] == '\0')
break;
endIndex = beginIndex;
while (str[endIndex] && !isspace(str[endIndex])){
++endIndex;
}
int len = endIndex - beginIndex;
char *tmp = calloc(len + 1, sizeof(char));
memcpy(tmp, &str[beginIndex], len);
arr[wordCnt++] = tmp;
beginIndex = endIndex;
if (wordCnt == maxWords)
break;
}
return wordCnt;
}
int main(void) {
char *arr[10];
int i;
int n = split("1st 2nd 3rd", arr);
for(i = 0; i < n; ++i){
puts(arr[i]);
free(arr[i]);
}
return 0;
}
这篇关于分割线进入的话+ C数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!