It is necessary to determine whether the string is a palindrome. A palindrome is a string that is written in the same way from left to right and from right to left (including the empty one). When defining " palindrome " strings should be considered only letters and numbers. And spaces, punctuation marks, and also the register of characters should be ignored.

Sample Input: Madam, I'm Adam!

Sample Output: true

You can remove spaces with .replace(" ",""); and how to filter a line from punctuation marks? common code that works on lines without punctuation:

 import java.util.Arrays; public class Arr { public Boolean vozvrat(String A){ String B=""; String C=A.replace(" ",""); char[] mass =C.toCharArray(); char[] mass2=new char[mass.length]; for ( int i =mass.length-1; i>= 0;){ for(int j=0;j<mass2.length; j++){ mass2[j]=mass[i]; i--; B+=mass2[j]; } } System.out.println(B); System.out.println(C); return B.equalsIgnoreCase(C); } public static void main(String args[]){ Arr C=new Arr(); System.out.println(C.vozvrat("Madam' I'm Adam")); } } 
  • 2
    It seems to me alone that this task without cycles is perfectly solved? - ArcherGodson

5 answers 5

The method determines whether the string is a palindrome. Solution in one line.

  • replaceAll("\\W","") : remove all unnecessary characters from the string (punctuation, spaces, etc.);
  • new StringBuilder : create a second string, but re-sorted in the reverse order using the reverse() method;
  • equalsIgnoreCase : compare them with each other, ignoring case.

Code:

 public static boolean isPalindrome(String text) { return text.replaceAll("\\W","") .equalsIgnoreCase(new StringBuilder(text.replaceAll("\\W","")) .reverse().toString()); } 
  • Try to write more detailed answers. Explain what is the basis of your statement? - Nicolas Chabanovsky

Here is the solution to your problem:

 import java.util.regex.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { BufferedReader inputStream = new BufferedReader(new InputStreamReader(System.in)); try { System.out.print("Sample input: "); String input = inputStream.readLine(); System.out.print("Sample output: "); System.out.print(isPalindrome(input)); } catch (IOException exception) { System.err.println("Input error"); } } public static boolean isPalindrome(String input) { Pattern pattern = Pattern.compile("\\w+"); Matcher matcher = pattern.matcher(input); StringBuilder builder = new StringBuilder(); while (matcher.find()) builder.append(matcher.group()); String result = builder.toString(); String reverseResult = builder.reverse().toString(); if(result.compareToIgnoreCase(reverseResult) == 0) return true; return false; } } 

UPD : I didn’t take your code into account, you can copy my isPalindrome method isPalindrome .

  • @typemoon is actually a regular expression. I selected all the letters from the string and blind them together using StringBuilder , and then compared the resulting string ( builder.toString() ) with an inverted string ( builder.reverse().toString() ). The bad of you Troll, there is no passage in the cycle from the beginning and from the end. - Umed

thanks Alexander Smirnov but it will be more understandable

 public static boolean isPalindrome(String text) { text = text.replaceAll("\\W","");//удаляем все ненужное StringBuilder strBuilder = new StringBuilder(text); strBuilder.reverse(); //переворачиваем строку String invertedText = strBuilder.toString();//присваиваем перевернутую строку return text.equalsIgnoreCase(invertedText) ;//возвращаем сравнение двух строк вне зависимости от регистра } 
    1. Make a regular schedule that includes only letters and numbers.
    2. Break the string into an array.
    3. In the loop, go over the array, checking for the condition of entering the regular season. If not included, replace with "" .
    4. As a result, you have a string at the output without spaces or punctuation.
    • It seems to me more correct to literally compare a string moving from its beginning and end to the middle and use the Character.isLetterOrDigit method to discard unnecessary characters. - avp
    • why not go all the way from start to finish? - ketchyn
    • Perhaps you are right) But you first need to throw out too much, and then move to the middle) - YuriySPb
    • "Make a regular season," Plz can not be in more detail (just recently started to learn java) - ketchyn
    • 3
      No regulars are needed. Generally not needed. It is better to throw "on the go." Those. for(i = 0, j = str.length() - 1; i < j; i++, j--) { while (i < j && badchar(str.charAt(i)) i++; while(...) j--; ... / I think the idea is clear how to compare in lowcase you will find - avp

    thank you

     import java.util.Arrays; public class Arr { public Boolean vozvrat(String A) { String K = ""; String B = ""; char[] mass0 = A.toCharArray(); for (int l = 0; l < mass0.length - 1; l++) { if (Character.isLetterOrDigit(mass0[l]) == false) { l++; } K += mass0[l]; } K = K.replace(" ", ""); char[] mass = K.toCharArray(); char[] mass2 = new char[mass.length]; for (int i = mass.length - 1; i >= 0;) { for (int j = 0; j < mass2.length; j++) { mass2[j] = mass[i]; i--; B += mass2[j]; } } System.out.println(A); System.out.println(K); System.out.println(B); return B.equalsIgnoreCase(K); } public static void main(String args[]) { Arr C = new Arr(); System.out.println(C.vozvrat("Madam, I'm Adam!")); } }