W
W
whoisyourfriend2020-05-14 23:37:49
Swift
whoisyourfriend, 2020-05-14 23:37:49

How to check if a word is a palindrome?

It is necessary to find out whether a word, for example "Cossack", is a palindrome.
I wrote a code that compares characters in an array using if. But such code will not work if it is a string of 1000 characters.

I found a solution on the Internet, how it could be solved through a function, but my dz provides that I do not yet own the functions.
Please tell me how to solve this problem using for in.
There was an idea to compare the first character of the array with the last one, but I did not understand how to write it in for in.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
iMaximus, 2020-05-15
@whoisyourfriend

If needs to be used where it is really needed, in a normal office, for several nested ifs in functions they kick with their feet :)
This is done in 3 lines

let str = "казак"
let reversrdStr = String(str.reversed())
print((str == reversrdStr) ? "палидром" : "не палидром")

Or do you need to pervert for learning, breaking into symbols? :)
Added, then so.
let str = "казак"
let charsters =  Array(str)
let maxIndex = charsters.count - 1
var newStr = ""

for i in 0...maxIndex{
    newStr = newStr + String(charsters[maxIndex-i])
}
print((str == newStr) ? "палидром" : "не палидром")

You can compare character-by-character without making a new word.
Using the second example, it is easy to understand how to do it yourself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question