2012-06-22 47 views
0

這是Ansi C.我給了一個字符串。我應該創建一個方法,該方法返回指向所述字符串的每個單詞的開頭的字符指針數組。我不允許使用malloc,而是告知輸入的最大長度爲80在ANSI C使用指針的Tokenize字符串C

而且,在任何人火焰我沒有搜索的論壇,我不能使用的strtok :(

char input[80] = "hello world, please tokenize this string" 

和方法的輸出應該有6個元素;

output[0] points to the "h", 
output[1] points to the "w", 

我應該怎麼寫的方法

另外,我需要一個類似的方法來處理來自最多110行的文件的輸入。

+0

這聽起來像功課? – nhahtdh

+0

這是功課嗎?你已經嘗試了什麼? – peacemaker

+0

是的,這是作業,但到期日期已過。現在只是出於好奇而問。 – bxio

回答

1

僞代碼:

boolean isInWord = false 
while (*ptr != NUL character) { 
    if (!isInWord and isWordCharacter(*ptr)) { 
     isInWord = true 
     save ptr 
    } else if (isInWord and !isWordCharacter(*ptr)) { 
     isInWord = false 
    } 
    increment ptr 
} 

isWordCharacter檢查字符是否是單詞或不的一部分。根據您的定義,它只能是字母字符(將part-time識別爲2個單詞),或者可能包含-(將part-time識別爲一個單詞)。

0

因爲它的功課這裏,你可能需要的東西的一部分:

char* readPtr = input; 
char* wordPtr = input; 
int wordCount = 0; 
while (*readPtr++ != ' '); 
/* Here we have a word from wordPtr to readPtr-1 */ 
output[wordCount++] = /* something... :) */ 

你需要在一個循環,必須考慮如何移動到下一個詞,併爲您輸入的結束。

+0

檢查'!='''不是一個好主意,因爲字符串可以是'「逗號,,,,很多」,並且您將會識別出'',一個字。 – nhahtdh

+0

這是真的,相反,我會建議創建一個分隔符數組並檢查readPtr對這些。這只是一個如何開始的建議:) – peacemaker