1
For ex: "__I_love___India___"; 

in this string i want to remove leading and trailing spaces completely and multiple spaces with in the string in java.

i.e. output should be

"I love India";

Vikas Gupta
  • 1,183
  • 1
  • 10
  • 25
yashu
  • 29
  • 1
  • 7
  • One google search of "java regex remove extra spaces" returned first results of [Java how to replace 2 or more spaces with single space in string and delete leading spaces only](https://stackoverflow.com/a/2932439/6577822) – fjoe Sep 04 '17 at 04:55
  • 1
    You can use `replaceAll()` to replace multiple spaces with single spaces and use `trim()` to get rid of leading and trailing spaces. But please be careful about using "please provide code" in your question, because you are not our employer and we are not a code-writing service. That will often get you downvotes. I've given you some strong hints, now go look up the javadoc and do the rest of the work yourself. – ajb Sep 04 '17 at 04:55
  • @fjoe Note that if I wanted to remove leading and trailing spaces and found a Google hit that said "delete leading spaces only", I might not look at that question. It turns out to give the right answer, but the poster of that question botched the title. – ajb Sep 04 '17 at 04:58
  • P.S. I went ahead and changed the title of the other question. Now maybe others can find it. – ajb Sep 04 '17 at 05:01
  • Stop down voting people are far too quick to criticise lately. Instead be helpful. – jamesc Sep 04 '17 at 05:14
  • Fo4r gods sake you lot. Help people please! This is a new ish user. Welcome with constructive criticism. I'm on a mission to make this a friendlier place and more welcoming to newbies. – jamesc Sep 04 '17 at 05:22
  • @jamesc I agree with your idea but he is a member for 11month... as already posted a question a couple of month ago. So he had the time to read the FAQ about asking question. This is generaly why people downvote a "new user", skipping the introduction of the rules. I bet if you take your car without having a license, the cops won't agree to let you go just because you never read the specific law about driving a car. – AxelH Sep 04 '17 at 06:59
  • @ajb, Thank you very much for suggestion. and sorry for the way i asked. – yashu Sep 04 '17 at 13:16

5 Answers5

2

Another way is to use StringTokenizer with a space as a token separator. Read each token and write it back to StringBuilder.

import java.util.*;

class Words
{

    /**
     * Convenience method. 
     */
    public static StringBuilder deduplicateSpaces(String text)
    {
        return deduplicateDelimiters(text, " ");
    }

    public static StringBuilder deduplicateDelimiters(String text, String delim)
    {
        StringTokenizer       st = new StringTokenizer(text, delim);
        StringBuilder         sb = new StringBuilder();
        boolean         firstRun = true;

        while (st.hasMoreTokens())
        {
            sb.append(firstRun? "" : delim)  //prevent delimiter on the first token
              .append(st.nextToken()      ); //append token itself
            if (firstRun) { firstRun = false; }
        }

        return sb;
    }

    public static void main (String[] args)
    {
        String textS = "    A     bbbb    ccccc   ";
        String textU = "____A_____bbbb____ccccc___";

        System.out.println(deduplicateSpaces(textS));

        System.out.println(deduplicateDelimiters(textU, "_"));
    }
}

Output is:

A bbbb ccccc
A_bbbb_ccccc
2

Method trim () removes leading and trailing spaces. In order to remove duplicate spaces from the middle of the string you can use regular expression.

s2 = s1.replaceAll ("\\s+", " ").trim ();

AlexR
  • 114,158
  • 16
  • 130
  • 208
  • Thank you Alex. but dint want to use builtin methods.instead, i want use user defined method to remove leading spaces – yashu Sep 04 '17 at 13:19
1

Try this logic:

String input = "I love   India    ";
input = input.trim().replaceAll("\\s+", " ");

The idea here is use two separate operations for handling whitespace at the beginning/end and whitespace between words. We want to completely remove whitespace at the beginning/end and String#trim() does that nicely. Then, between words only a single space should appear, and a regex replacement handles this case.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

You can try one of these:

  • Pure Java - String after = before.trim().replaceAll("\\s+", " ");
  • Pure Java - String after = before.replaceAll("\\s{2,}", " ").trim();
  • Apache commons lang3 - String after = StringUtils.normalizeSpace(String str);
  • ...
Tooraj Jam
  • 1,592
  • 14
  • 27
0

Try replaceAll("\\s{2,}", " ").trim(); where str is a String variable containing the text you want to strip white space from and use trim for leading and trailing white space Updated as a result of comments as I forgot to replace multiple white space with a single space

jamesc
  • 12,423
  • 15
  • 74
  • 113
  • 1
    This will remove all whitespace from the string. – clemens Sep 04 '17 at 05:03
  • 1
    @macmoonshine No it won't. You were too quick to vote and comment. Put your gun away dude :) – jamesc Sep 04 '17 at 05:09
  • 1
    You were shot before you edited your answer - you are now dead ;-) – Scary Wombat Sep 04 '17 at 05:16
  • @ScaryWombat Yeah, people are getting far too quick to criticise lately. Been noticing a lot of newbies getting down voted instead of helped. It's disgraceful. this is supposed to be a community. And did the downvoters correct theor do0wn vote? No. Why not? – jamesc Sep 04 '17 at 05:17
  • What are you meaning? – Scary Wombat Sep 04 '17 at 05:18
  • @ScaryWombat. My gun misfired lol :) – jamesc Sep 04 '17 at 05:20
  • Almost upvote you for your witty comments – Scary Wombat Sep 04 '17 at 05:21
  • As I gave my comment, your answer was _wrong_. – clemens Sep 04 '17 at 05:23
  • @mamoonshine, yes I know. I had to correct the answer. Thank's for the up votes. Just wanted to make the point that it's too easy to criticise. I don't care about me but the OP is a newish user and really needed help, didn't know how to ask for it properly yet we are all bright enough to give the right answer so rather than shooting how about helping constructively. Anyway, Raising the white flag of peace now. – jamesc Sep 04 '17 at 05:27