finding letters in a word


I wanted to input a word and have it match another word and print out the miss matched letters in a different color. for example if its matching the word "hello" and I type "holino" I want it to print out "hello" with the el in a different color. the example below only compares two words and prints out the letter in different color but if the miss spelled word is larger or shorter then the the word that is being compared to it wont work. how can i get it to work?

char first_word[]="hello";
char defintion[]="holino";
int word_length=5;

for (int loop=0; loop<word_length; loop++)
{

if (first_word[loop]==defintion[loop])
{
cout <<first_word[loop];


}
else {
cout <<"\x1b[31;1m";
cout << first_word[loop];
cout <<"\033[0m";
}
What you got there is a form of the longest common subsequence problem. Check if the letters are or not part of the subsequence and color them accordingly.

https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
Last edited on
so how can i fix that?
C++ doesn't have any inherent color handling methods, so any solution would be platform dependent. Below for Windows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <string>
#include <windows.h>//HANDLE, SetConsoleTextAttribute

char printColorGreen(const char c)
{
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hConsole, FOREGROUND_INTENSITY | FOREGROUND_GREEN);//green
    return c;
}
void printColorWhite()
{
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hConsole, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);//white
}

int main()
{
    std::string first_word{}, definition{};

    std::cout << "Enter first word: \n";
    getline(std::cin, first_word);
    std::cout << "Enter definition: \n";
    getline(std::cin, definition);

    for (size_t i = 0; i < std::min(first_word.size(), definition.size()); ++i)
    {
        if(first_word[i] == definition[i])
        {
            std::cout << printColorGreen(first_word[i]);
        }
        else
        {
            printColorWhite();
            std::cout << first_word[i];
        }
    }
    if(definition.size() < first_word.size())
    //check definition.size() < i <= first_word.size() no garbage values to produce false equality
    {
        printColorWhite();
        std::cout << first_word.substr(definition.size());
    }
    printColorWhite();
}
thanks a million gunnerfunner. that's all i need to know... keep up the good work..
Last edited on
Topic archived. No new replies allowed.