문제

for a college project, I am doing a spelling test for children and i need to give 1 mark for a minor spelling error. For this I am going to do if the spelling has 2 characters wrong. How can I compare the saved word to the inputed word?

char wLetter1 = word1.charAt(0);
char iLetter1 = input1.charAt(0);


char wLetter2 = word1.charAt(1);
char iLetter2 = input1.charAt(1);

I have started out with this where word1 is the saved word and input1 is the user input word. However, if I add lots of these, if the word is 3 characters long but I am trying to compare the 4th character, I will get an error? Is there a way of knowing how many characters are in the string and only finding the characters of those letters?

도움이 되었습니까?

해결책

Just use a for loop. Since I'm assuming this is about JavaScript, calling charAt() with an index out-of-bounds will just return the empty string "".

To avoid a out-of-bounds exception you'll have to iterate up until the lower of the lengths:

int errs = Math.abs(word1.length - input1.length);
int len = Math.min(word1.length, input1.length);
for (int i = 0; i < len; i++) {
    if (word1.charAt(i) != input1.charAt(i)) errs++;
}
// errs now holds the number of character mismatches
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top