我正在解析文本文件:
Hello, this is a text file.
并通过将文件转换为char []来创建。现在我想获取数组,遍历它,并创建一个数组数组,将文件分成单词:
string[0] = Hello
string[1] = this
string[2] = is
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "TextReader.h"
#include <ctype.h>
void printWord(char *string) {
int i;
for (i = 0; i < strlen(string); i ++)
printf("%c", string[i]);
printf("\n");
}
void getWord(char *string) {
char sentences[5][4];
int i;
int letter_counter = 0;
int word_counter = 0;
for (i = 0; i < strlen(string); i ++) {
// Checks if the character is a letter
if (isalpha(string[i])) {
sentences[word_counter][letter_counter] = string[i];
letter_counter++;
} else {
sentences[word_counter][letter_counter + 1] = '\0';
word_counter++;
letter_counter = 0;
}
}
// This is the code to see what it returns:
i = 0;
for (i; i < 5; i ++) {
int a = 0;
for (a; a < 4; a++) {
printf("%c", sentences[i][a]);
}
printf("\n");
}
}
int main() {
// This just returns the character array. No errors or problems here.
char *string = readFile("test.txt");
getWord(string);
return 0;
}
这就是它的回报:
Hell
o
this
is
a) w
我怀疑这与指针和东西有关。我来自强大的Java背景,所以我还是习惯了C。
答案 0 :(得分:3)
使用sentences[5][4]
,您将sentences
的数量限制为5,将每个单词的长度限制为4.您需要将其设置为更大才能处理更多更长的单词。试试sentences[10][10]
。您也没有检查输入的单词是否不长于sentences
可以处理的单词。使用更大的输入,这可能导致堆溢出和访问违规,请记住C不会检查你的指针!
当然,如果您要将此方法用于包含较大字词的较大文件,则需要将其设置为or allocate it dymanically。
答案 1 :(得分:0)
不使用strtok的示例:
void getWord(char *string){
char buff[32];
int letter_counter = 0;
int word_counter = 0;
int i=0;
char ch;
while(!isalpha(string[i]))++i;//skip
while(ch=string[i]){
if(isalpha(ch)){
buff[letter_counter++] = ch;
++i;
} else {
buff[letter_counter] = '\0';
printf("string[%d] = %s\n", word_counter++, buff);//copy to dynamic allocate array
letter_counter = 0;
while(string[++i] && !isalpha(string[i]));//skip
}
}
}
使用strtok版本:
void getWord(const char *string){
char buff[1024];//Unnecessary if possible change
char *p;
int word_counter = 0;
strcpy(buff, string);
for(p=buff;NULL!=(p=strtok(p, " ,."));p=NULL){//delimiter != (not isaplha(ch))
printf("string[%d] = %s\n", word_counter++, p);//copy to dynamic allocate array
}
}