Oct. 7 - Oct. 9
In order to check if str
is a palindrome, you must check if the first character is the same as the last character,
then check if the second character is the same as the second to last character, then check if the third character is the same
as the third to last character, and so forth.
As a reminder, you can get a single character from a string by using either array brackets ([ ]
) or the charAt
method of a String. This means that both of these will get the character at index 3:
var c1 = str.charAt(3); var c2 = str[3];
Therefore, to check for a palindrome, you must:
false
immediately.
false
.
Therefore, the string must be a palindrome and you should return true
.
Step 2 in the previous list can be challenging. This table may help you understand how you need to complete Step 2:
Example value of str |
i | ith character | ith character from the end | Equal? |
---|---|---|---|---|
"racecar" |
0 |
[i] == [0] == "r" |
[str.length - 1 - i] == [7 - 1 - 0] == [6] == "r" |
Yes |
1 |
[i] == [1] == "a" |
[str.length - 1 - i] == [7 - 1 - 1] == [5] == "a" |
Yes | |
2 |
[i] == [2] == "c" |
[str.length - 1 - i] == [7 - 1 - 2] == [5] == "c" |
Yes | |
3 |
[i] == [3] == "e" |
[str.length - 1 - i] == [7 - 1 - 3] == [4] == "e" |
Yes | |
4 |
[i] == [4] == "c" |
[str.length - 1 - i] == [7 - 1 - 4] == [2] == "c" |
Yes | |
5 |
[i] == [5] == "a" |
[str.length - 1 - i] == [7 - 1 - 5] == [1] == "a" |
Yes | |
6 |
[i] == [6] == "r" |
[str.length - 1 - i] == [7 - 1 - 6] == [0] == "r" |
Yes | |
All equal, therefore return true
|
||||
"cs105" |
0 |
[i] == [0] == "c" |
[str.length - 1 - i] == [5 - 1 - 0] == [4] == "5" |
No |
"c" != "5" , therefore return false immediately
|
On your lab6.html web page, use the Palindrome Checker to test if your function works! Make sure to try both words that are palindromes and words that are not palindromes.
To submit your lab, you must submit your lab6.js to the CS 105 website. You should submit ONLY .js file. You do not need to submit the other files in the folder. Click here to submit the lab!