Using a simple scanner, reading a string with spaces, how come .trim() method isn't working?
import java.util.Scanner;
import java.lang.String;
public class Test
{
public static void main(String[] args)
{
char[] sArray;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a Palindrome : ");
String s = scan.nextLine();
s = s.trim();
sArray = new char[s.length()];
for(int i = 0; i < s.length(); i++)
开发者_JAVA技巧 {
sArray[i] = s.charAt(i);
System.out.println(sArray[i]);
}
}
}
Trim doesn't work how you expect it to. trim()
only removes whitespace from the ends of the string.
The documentation for trim()
:
Returns a copy of the string, with leading and trailing whitespace omitted.
To remove all whitespace try the following instead of calling trim()
:
s = s.replaceAll("\\s+", "");
This uses a very simple regular expression to remove all whitespace anywhere in the string.
The trim
function removes leading and trailing spaces, not all spaces.
If you want to remove all spaces, you can call s = s.replaceAll(" ", "")
.
great answer jjnguy and slals
I now use
myinput = myEditTextbox.getText().toString;
myinput = myinput.replaceAll("\\S+", "");
to clean out all spaces accidentally left in an edittext box by the user. It also directed me to learn about regular expressions that I didn't know about. Thanks
精彩评论