开发者

Split words and capitalize first character

开发者 https://www.devze.com 2023-02-24 09:00 出处:网络
I\'m getting user input that I need to format. I need to remove all leading/trailing spaces and I need to capitalize the first letter of each word.

I'm getting user input that I need to format. I need to remove all leading/trailing spaces and I need to capitalize the first letter of each word.

Here is what I'm trying, however... if you input something with 2 spaces between words, it crashes. How might I solve this?

String formattedInput = ""开发者_如何学编程;
String inputLineArray[] = inputLine.getText().toString().trim().split("\\s");
for (int d=0; d<inputLineArray.length; d++) {
    formattedInput = formattedInput.trim() + " " +   
            inputLineArray[d].trim().substring(0,1).toUpperCase() +
            inputLineArray[d].trim().substring(1).toLowerCase();
}


Your code is blowing up on multiple spaces because when you split you're getting a member in your array that is an empty string "hello there" when split becomes array[0] = "hello", array[1] = "", array[2] = "there".

So when you do substring(0,1) you should get an IndexOutOfBoundsException.

Try changing your split("\\s") to split("\\s+") this way your multiple spaces get picked up in the regex and thrown out.

Edit:

This also will let you get rid of the .trim() inside your loop since all of the spaces will be taken care of by the split.


tokenize the string and split by space " " and then take each iteration and capitalize it and then put it back together again

read all about string tokenization here

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号