Hello.

The task is to compare the first letter of the word with the last.

Example: anna begins with the letter a and ends with the letter a and these words are 2 of us.

Thank you for your reply. :)

void main(){ char str[] = "hello to anna annna"; int total = strlen(str); int counter = 0; char temp = str[0]; for (int i = 0; i < total; i++){ if (str[i] == ' '){ if (str[0] == str[i-1]){ counter++; i = 0; } } } printf("%d",counter); } 
  • wrong algorithm, it is necessary to be easier, write down the first letter and look for the space, compare the letter to the previous one. - zb '
  • You are right, I just want to do, say, the first letter is on id 6 words, the last one is on id 9. I have to write different letters every time, I don’t get the right code: h = 0 e = 1 l = 2 l = 3 e = 4 '' = 5 a = 6 -> what we need n = 7 n = 8 a = 9 -> what we need - David Kern

2 answers 2

 #include <iostream> #include <string> using namespace std; int main() { char str[] = "hello to anna annna and ana test to ana "; string s; // сюда мы будем помещать найденные слова int count = 0; // счетчик слов с одинаковой первой и последней буквой // разделяем на слова и помещаем их в строку for (size_t i = 0; i < strlen(str); i++){ if (str[i] != ' ') // если это не пробел s.push_back(str[i]); // помещаем символы в строку else { cout << "->" << s << "<-" << endl; // отладка // сравниваем первую и последнюю букву найденного слова if ((s.size() != 0) && (s[0] == s[s.size() - 1])){ ++count; } s.clear(); } } // проверяем первую и последнюю букву после последней итерации if ((s.size() != 0) && (s[0] == s[s.size() - 1]) && (s[s.size() - 1] != ' ')){ cout << "->" << s << "<-" << endl; // отладка ++count; } cout << count << endl; // результат return 0; } 
     #include <stdio.h> // puts #include <string.h> // strtok int main(void) { char str[] = "hello to anna annna and ana test to ana "; char* i; for (i = strtok(str, " "); i != NULL; i = strtok(NULL, " ")) { int last = strlen(i) - 1; if (last != -1 && i[0] == i[last]) { puts(i); } } return 0; }