因此,任務如下:
找出文本中第一個字符和最后一個字符相同的單詞數。
為了做到這一點,我認為我首先應該拆分文本并創建單獨的單詞陣列。
例如,字串是:
《你好再見河狗級》
我想拆分它并獲得以下陣列:
{“你好”、“再見”、“河流”、“狗”、“水平”}
我有拆分字串的代碼:
#include<stdio.h>
#include <string.h>
int main() {
char string[100] = "hello goodbye river dog level";
// Extract the first token
char * token = strtok(string, " ");
// loop through the string to extract all other tokens
while( token != NULL ) {
printf( " %s\n", token ); //printing each token
token = strtok(NULL, " ");
}
return 0;
}
但是,它只是列印這些單詞,我需要將每個單詞附加到某個陣列中。該陣列不應該是固定大小的,因為我可以添加文本需要的盡可能多的元素。這個怎么做?
uj5u.com熱心網友回復:
我看不出有什么理由分裂成文字。只需迭代字串,同時保留一個標志,告訴您是在單詞內部還是外部(即狀態變數)。然后在迭代時保留第一個和最后一個字符的變數。當你用完一個單詞或到達字串結尾時比較它們。
一個簡單的方法可能如下所示:
#include <stdio.h>
int count(const char* s)
{
int res = 0;
int in_word = 0;
char first;
char last;
while(*s)
{
if (in_word)
{
if (*s == ' ')
{
// Found end of a word
if (first == last) res;
in_word = 0;
}
else
{
// Word continues so update last
last = *s;
}
}
else
{
if (*s != ' ')
{
// Found start of new word. Update first and last
first = *s;
last = *s;
in_word = 1;
}
}
s;
}
if (in_word && first == last) res;
return res;
}
int main(void)
{
char string[100] = "hello goodbye river dog level";
printf("found %d words\n", count(string));
return 0;
}
輸出:
found 2 words
注意:當前代碼假定單詞分隔符始終是空格。此外,代碼不會處理諸如此類的東西, .。但是所有這些都可以很容易地添加。
uj5u.com熱心網友回復:
這是一個基于現有strtok代碼的簡單(但幼稚)的實作。它不僅計算而且指出找到了哪些單詞,方法是將指向它們的指標存盤在單獨的指標陣列中。
這是有效的,因為strtok就地更改了字串,用空終止符替換空格。
#include <stdio.h>
#include <string.h>
int main(void)
{
char string[100] = "hello goodbye river dog level";
char* words[10]; // this is just assuming there's not more than 10 words
size_t count=0;
for(char* token=strtok(string," "); token!=NULL; token=strtok(NULL, " "))
{
if( token[0] == token[strlen(token)-1] ) // strlen(token)-1 gives index of last character
{
words[count] = token;
count ;
}
}
printf("Found: %zu words. They are:\n", count);
for(size_t i=0; i<count; i )
{
puts(words[i]);
}
return 0;
}
輸出:
Found: 2 words. They are:
river
level
uj5u.com熱心網友回復:
strtok 基于 Alexander 的代碼。
#include <stdio.h>
#include <string.h>
int main(void)
{
char string[] = "hello, goodbye; river, dog; level.";
char *token = strtok(string, " ,;.");
int counter =0;
while( token != NULL )
{
if(token[0]==token[strlen(token)-1]) counter ;
token = strtok(NULL, " ,;.");
}
printf("found : %d", counter);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/529515.html
標籤:数组C细绳
上一篇:將空終止符附加到C 字串
下一篇:如何更新和更改當前域陣列串列
