[英]Printing Array of Strings
我正在解析一個文本文件:
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。
使用sentences[5][4]
您將sentences
的數量限制為5個,每個單詞的長度限制為4個。您需要使其更大,才能處理越來越多的單詞。 試試sentences[10][10]
。 您也不會檢查輸入的單詞是否不超過sentences
可以處理的長度。 如果輸入較大,可能會導致堆溢出和訪問沖突,請記住,C不會為您檢查指針!
當然,如果要將這種方法用於帶有較大單詞的較大文件,則需要使其增大或動態分配 。
不使用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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.