Amit Bhati
Amit Bhati

Reputation: 5649

How to implement trim() method in java by using only substring() method

I know this question is quite silly, but in an interview I was told to implement trim() method without using any method from String class except substring() method.

I approached this problem by using toCharArray() and then identifying the first and last valid character of String. But was told not to use toCharArray() method.

Could anyone suggest some approach to do it.

Overriden methods of Objects class are allowed like equals() and hashCode().

Upvotes: 3

Views: 2932

Answers (6)

Genti Saliu
Genti Saliu

Reputation: 2723

String untrimmed = "  some   string   ";
String trimmed = "";

String innerSpaces = "";
boolean wordBoundary = true;

try {
    for (int i = 0; ; i++) {
        String substr = untrimmed.substring(i, i + 1);

        if (!substr.equals(" ") && !substr.equals("\t") && 
               !substr.equals("\n") && !substr.equals("\r")) {

            trimmed += innerSpaces + substr;
            wordBoundary = false;
            innerSpaces = "";
        }
        else if (!wordBoundary) {
            innerSpaces += substr;
        }
    }
}
catch (IndexOutOfBoundsException e)  { }

System.out.println(trimmed);

Upvotes: 5

Mshnik
Mshnik

Reputation: 7032

It's not too hard if you start by redefining length() and charAt() in terms of substring... Of course it's inefficient (length now takes O(n^2)), but it gets the job done and as a bonus defines both length() and charAt()

  public static int length(String s) {
    for(int i = 0; i < Integer.MAX_VALUE; i++) {
      try {
        s.substring(i);
      }catch(StringIndexOutOfBoundsException e) {
        return i - 1;
      }
    }
    return Integer.MAX_VALUE;
  }

  public static char charAt(String s, int idx) {
    String c = s.substring(idx, idx+1);
    return (char)c.hashCode();
  }

  public static String trim(String s) {
    final int length = length(s);
    int startIndex;
    int endIndex;

    for(startIndex = 0; startIndex < length; startIndex++) {
      char c = charAt(s, startIndex);
      if(! Character.isWhitespace(c)) {
        break;
      }
    }

    for(endIndex = length; endIndex > startIndex; endIndex--) {
      char c = charAt(s, endIndex - 1);
      if(! Character.isWhitespace(c)) {
        break;
      }
    }
    return s.substring(startIndex, endIndex);
  }

Upvotes: 0

z7r1k3
z7r1k3

Reputation: 737

A very inefficient solution, but here it goes.

You said in the comments you can use the .equals() method. So here's my elaborate solution:

You know those mileage counters in cars? The ones that go 0000, 0001, 0002... etc.? Mimic that with a char arrayList.

Start with size 1, and go through each character, using mainString.equals(charArrayList.toString()) to compare it. If you get through all the characters, and no match, increase size by one and repeat. Once you have a match, you can check for whitespace characters at the beginning and end.

Please keep in mind I know this isn't efficient, but it works. Even if it takes a year :)

Hope this helps!

Upvotes: 0

Dici
Dici

Reputation: 25950

Hacky, but the question is stupid anyway :

public static String trim(String s) {
    StringBuilder sb = new StringBuilder(s);
    int start, end;
    for (start = 0; start < sb.length() && Character.isWhitespace(sb.charAt(start)); start++);
    for (end = sb.length() - 1; end > start && Character.isWhitespace(sb.charAt(end)); end--);
    return sb.substring(start, end + 1);
}

System.out.println(trim("   \n \t trim me  \t "));

Upvotes: 1

Joop Eggen
Joop Eggen

Reputation: 109547

Of course substring would be needed for the trimmed result.

Without any method of String it would be hard to find possible spaces at both ends.

Remains:

  1. Outer handling:

    Some form of

    Pattern pattern = Pattern.compile("\\s*(\\S*)\\s*"); // Pattern not okay
    Matcher m = pattern.matcher(string);
    string = m.matches()? m.group(1) : string;
    

    Or:

    Set<String> set0 = new HashSet<>();
    set0.add(string);
    Set<String> set = new HashSet<>();
    try {
        set.add(" " + string.substring(1));
        if (set0.contains(set)) {
            ...
    } catch (IndexOutOfRangeException e) { ... }
    
  2. Using a method of a super class of String. However there is no one that is not overriden by String itself. Maybe the following would be allowable:

    CharSequence cs = string;
    // Use cs.charAt or Whatever
    

Both seem legalistic solutions. I would lave to know their solution - or was it an impossible-answer question.

Upvotes: 4

biziclop
biziclop

Reputation: 49734

You can cheat and instead call Strings methods indirectly:

StringBuilder sb = new StringBuilder(sb);
for (int i = 0; i < sb.length(); i++) {
   char ch = sb.charAt(i);
   ...
}

If anyone asks, you aren't calling any methods on String, not even substring(). StringBuilder does it for you. :)

All in all, this is a terrible question, I wouldn't worry about it.

Upvotes: 0

Related Questions