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"