-1

I'm fairly new to java and I'm trying to work on an assignment for my comp class, but it's been stumping me. The assignment calls for me to:

Write a method trim(String s) that returns a version of the parameter s with all extra spaces removed (this includes leading and trailing zeroes, as well as any extra spaces within the body of each string). It specifies that the trim method of the String class shouldn't be used. Additionally, the only methods of the String class we're allowed to use are the CharAt, equals, length, and substring methods.

public static String trim(String s) {
    String newString = "";
    for(int i = 0;  i < s.length(); i++) {
        if(s.charAt(i) != ' ') {
            newString += Character.toString(s.charAt(i));
        }
    }
    return newString;
}

This is what I've gotten so far, but it removes every space instead of just extra spaces. I'm not asking for a full on solution to this problem as much as I'm looking for some kind of hint to help me out.

Edit: an example of expected outcome is:

input: trim("    coding  is    fun   ")
output: "coding is fun"
  • Simple approach would be to have two loops. One to check from the start and one to check from the end. Exit the loop when you find a character that is not a space. – clinomaniac Mar 15 '18 at 22:26
  • 1
    What does "extra" spaces mean? It'shardtoreadtextwithoutspaces,butpossible. – Johannes Kuhn Mar 15 '18 at 22:27
  • 1
    https://stackoverflow.com/questions/19612785/remove-white-space-from-string-without-using-trim-method – A J Mar 15 '18 at 22:31

1 Answers1

0

Hint 1: try to work out (in your head, on a piece of paper) the precise mathematical conditions under which you want to remove a character.

  • note that there are likely to be differences in the conditions for spaces at the beginning and end of the string.

Hint 2: consider solving the problem in 2 parts:

  • deal with the general case
  • deal with the "edge" cases; i.e. the exceptions to the general case
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216