-1

For example, I input "i Am Going \s\s\s to go tO the mall" the wide spaces(\s) must turn into single space.

    String f = line.substring(0,1).toUpperCase() + line.substring(1).toLowerCase();


    String[] split = f.split(" ");

    for(int i=0;i<split.length;i++){

        System.out.print (split[i] + " ");
    }
2se4n
  • 1
  • 1
  • 6

2 Answers2

0

Create a String toTitleCase(String) method that does the right thing to one word. It should handle special cases like turning tO to to, and keeping the lowercase, keeping all caps like FBI intact, and handle names like O'Neal, etc.

You can consider looking for an existing implementation instead.

Then do as you do: split the string, convert, join back:

String result = Arrays.stream(line.split(" "))
                .map(this::toTitleCase)
                .collect(Collectors.joining(" "));
9000
  • 39,899
  • 9
  • 66
  • 104
  • Thanks for your reply sir. My problem right now sir is that if I am going to input big spaces, the sentence must be turn in to single spacing. How will I do it? – 2se4n Sep 04 '19 at 20:41
  • Perhaps add a filter to avoid trimmed strings of length 0 from being included. – Andrew S Sep 04 '19 at 20:45
  • @AndrewS I tried .trim() to but doesn't work. – 2se4n Sep 04 '19 at 20:49
  • Add the filter to the stream, before the mapping, e.g.: `..)).filter(s -> !s.trim().isEmpty()).map(...` – Andrew S Sep 04 '19 at 20:56
0

You can use String object methods and regexp together.
Example:

String str1 = "i Am Going \t \t to go tO the mall";

//note : trim() eliminates only spaces at the beginning and end of the String
//removes extra spaces
String str2 = str1.trim().replaceAll(" +", " "); //way(1)
String str2 = str1.trim().replaceAll("\\s{2,}", " "); //way(2)

str2 = str1.replaceAll("\t", " "); //convert tab to space
str2 = str1.toLowerCase(); //convert all chars to lower case
str2 = str1.substring(0, 1).toUpperCase() + str1.substring(1); //convert first character to uppercase

Also you can use org.apache.commons:commons-lang library to capitalize your string simply:

StringUtils.capitalize(yourString);
Ghasem Sadeghi
  • 1,734
  • 13
  • 24
  • Strings are immutable. You may be on right track but please run your code first before posting it to see if it actually work. – Pshemo Sep 04 '19 at 20:48
  • Thanks sir. My code shown above is working but to remove the extra spaces is the thing I can't make to do. I tried your algo in removing, however output still the same. – 2se4n Sep 04 '19 at 20:53
  • @Pshemo I know Strings are immutable!It was only a hint! – Ghasem Sadeghi Sep 04 '19 at 20:56