簡體   English   中英

在ANSI C中使用指針對字符串進行標記

[英]Tokenize Strings using Pointers in ANSI C

這是在Ansi C中。我得到一個字符串。 我應該創建一個方法,該方法返回一個字符指針數組,該數組指向所述字符串的每個單詞的開頭。 我不允許使用Malloc,而是告訴我輸入的最大長度為80。

另外,在任何人因不搜索論壇而激怒我之前,我不能使用strtok :(

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

該方法的輸出應包含6個元素;

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

等等。

我應該如何編寫方法?

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

偽代碼:

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識別為一個單詞)。

因為這是家庭作業,所以這是您可能需要的一部分:

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

您將需要一個循環,並且必須考慮如何移至下一個單詞,並檢查輸入是否結束。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM