Check if a string is a palindrome

后端 未结 30 1472
星月不相逢
星月不相逢 2020-11-28 08:59

I have a string as input and have to break the string in two substrings. If the left substring equals the right substring then do some logic.

How can I do this?

30条回答
  •  [愿得一人]
    2020-11-28 09:14

    Here is an absolutely simple way to do this,

    1. Receive the word as input into a method.
    2. Assign a temp variable to the original value.
    3. Loop through the initial word, and add the last character to the reversal that you are constructing until the inital word has no more characters.
    4. Now use the spare you created to hold the original value to compare to the constructed copy.

    This is a nice way as u don't have to cast ints and doubles. U can just pass them to the method in their string representation by using the ToString() method.

    public static bool IsPalindrome(string word)
        {
            string spare = word;
            string reversal = null;
            while (word.Length > 0)
            {
                reversal = string.Concat(reversal, word.LastOrDefault());
                word = word.Remove(word.Length - 1);
            }
            return spare.Equals(reversal);
        }
    

    So from your main method, For even and odd length strings u just pass the whole string into the method.

提交回复
热议问题