Finding words with the same first character

北战南征 提交于 2020-06-29 02:41:44

问题


I've made an array and now I'm trying to compare first symbols of two strings and if it's true to print that word. But I got a problem:

Incompatible types in assignmentof "int" to "char"[20]"

Here is the code:

for ( wordmas= 0; i < character; i++ )
{
  do {
    if (!strncmp(wordmas[i], character, 1)
  }
  puts (wordmas[i]);
}

Maybe you guys could help me?


回答1:


There are several issues with your code:

  • You do not need strncmp to compare the first character - all you need is a simple == or !=.
  • Using a do without a while is a syntax error; you do not need a nested loop to solve your problem.
  • character is used to limit the progress of i in the outer loop, and also to compare to the first character of a word in wordmas[i]. This is very likely a mistake.
  • Assuming that wordmas is an array, assigning to wordmas in the loop header is wrong.

The code to look for words that start in a specific character should look like this:

char wordmas[20][20];
... // read 20 words into wordmas
char ch = 'a'; // Look for all words that start in 'a'
// Go through the 20 words in an array
for (int i = 0 ; i != 20 ; i++) {
    // Compare the first characters
    if (wordmas[i][0] == ch) {
        ... // The word wordmas[i] starts in 'a'
    }
}


来源:https://stackoverflow.com/questions/22127149/finding-words-with-the-same-first-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!