0

I want to remove the last 3 characters of the string if the string has the same prefix and suffix. eg: the string is "systemsys", it should print system. Few inputs I am trying : incgoogleinc. Not working for this input

import java.util.*;
public class Main {
    public  static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    String str = s.nextLine();
    if(str.length() > 3) { 
    if (str.startsWith(str.substring(0, 3)) == (str.substring(str.length()-3, str.length()-1))) {
        System.out.println(str.substring(0, str.length()-3));    
    } else {
        System.out.println(str);
}}}

Not working for different inputs : mictestingmic, comwebsitecom

Andreas
  • 154,647
  • 11
  • 152
  • 247
shantz
  • 25
  • 6

2 Answers2

2
if (str.startsWith(str.substring(0, 3)) == (str.substring(str.length()-3, str.length()-1))) {

str.startsWith(str.substring(0, 3)) returns a boolean (which happens to always be true because you're asking if it starts with the beginning of the string, which it always does).

str.substring(str.length()-3, str.length()-1))

For "mictestmic", this will return "mi", since substring() uses inclusive/exclusive ranges.

Therefore, your if statement evaluates to:

if (true == "mi") {

Instead, simply check if the string starts with the end:

if (str.startsWith(str.substring(str.length()-3))) {
Michael Bianconi
  • 5,072
  • 1
  • 10
  • 25
1

I don't know if you are allowed to use regex in your assignment, but it comes in handy here:

String input = "mictestingmic";
if (input.matches("(.+).*\\1")) {
    input = input.substring(0, input.length()-3);
}

System.out.println(input);

This prints mictesting, the last three characters removed, but mictestingcan would print the same input, since it does have a matching prefix and suffix.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • The code is working perfect! Thanks. I am still checking if there can be some alternatives for it as a beginner. – shantz Aug 15 '19 at 15:42
  • @ShantanuUdasi If input is `"mtestingm"`, the regex will be true, since the string does have the same prefix and suffix, the 1-character string `"m"`, and the code would then remove the last 3, resulting in `"mtesti"`. Is that really what should happen? --- Note that the answer follows the requirements in the question exactly, since the question never stipulates a specific length to the prefix/suffix, but the code in the question implies that prefix/suffix should be 3-character strings. Beware imprecise requirements. – Andreas Aug 15 '19 at 16:03
  • @Andreas Thanks for the comment, and I was thinking of this as well when I answered. If the requirement is for a three-length prefix/suffix, then we can try using the pattern `(.{3}).*\1` – Tim Biegeleisen Aug 15 '19 at 16:04
  • To combine the `matches` and `substring` calls, use `replaceFirst`, i.e. `input = input.replaceFirst("((.{3}).*)\\2", "$1");` – Andreas Aug 15 '19 at 16:06