142k views
2 votes
Write a program that asks the user to enter 2 words, then prints "Equal!" if the two words are the same (case-sensitive), "Different case" if the two words are the same (case-insensitive), “Close enough” if the two words are the same length and all but the last letter matches, and "Try again" otherwise.

User Mike Kor
by
5.1k points

2 Answers

7 votes

#include <bits/stdc++.h>

typedef std::string s;

s fi(s t, s m) {

if(t==m) return "Equal!";

if(strcasecmp(t.c_str(),m.c_str())==0) return "Different case!";

if(t.size()==m.size() && t.back()!=m.back()) {

for(int i=0;i<t.size()-1;i++) {

if(t.c_str()[i]==m.c_str()[i]) ;

else goto x;

}

return "Close enough!";

}

x: return "Try again!";

}

int main(int argc, char* argv[]) {

s idx,idy;

std::cin>>idx>>idy;

if(idx.size()!=idy.size()) std::cout << "Try again!\\";

else std::cout << fi(idx,idy) << std::endl;

return 0;

}

User Cozyss
by
5.8k points
7 votes

Answer:

Scanner scan = new Scanner(System.in);

System.out.println("Enter 2 strings:");

String word1 = scan.nextLine();

String word2 = scan.nextLine();

//equal strings

if (word1.equals(word2))

{

System.out.println("Equal!");

}

//same word, different case

else if (word1.toLowerCase().equals(word2.toLowerCase()))

{

System.out.println("Different case");

}

//same up to the last letter

else if (word1.substring(0, word1.length()-1).equals(word2.substring(0, word2.length()-1)))

{

System.out.println("Close enough");

}

//no equivalency

else

{

System.out.println("Try again");

}

Step-by-step explanation:

got 100% on the assignment so the code is correct

first scenario: both strings are equal, including the casing

second scenario: by setting both strings to lowercase if their cases don't match, they can be interpreted as having the same value by those standards in order to print out the statement

third scenario: .length() - 1 equates to the last letter of a string, so starting the range at 0 and ending at that will be read as the first letter to the letter before the last letter

fourth scenario: the strings do not fit into anything previously evaluated

User Ankit Mehta
by
4.7k points