Remove a specific space in a string

Asked

Viewed 756 times

6

I’m having trouble implementing replace in a String in Android Studio.

I need to remove a certain blank in the String.

Real examples:

  • 8 hrs 2 mins
  • 1 day 2 mins

I need the text to look like this:

  • 8hrs 2mins
  • 1day 2mins

If anyone can help me, I’d appreciate it.

  • You said you don’t know which sequences "hrs", "mins" come in the string. And which ones can come, you know? If you know, just call replace() for each one that will work smoothly. Otherwise, see my solution with regex.

  • Managed to resolve @dnsfirmino?

4 answers

10

String comEspaco = "8 hrs 2 mins";
String semEspaco = comEspaco.replace(" hr", "hr").replace(" min", "min");

Alternative solution with regex without depending on what comes after each space:

String comEspaco = "8 hrs 2 mins";
String semEspaco = comEspaco.replaceAll("([0-9]) ", "$1");

See working on Ideone.

  • Very good. I was doing my answer but never mind. Perfect.

  • Hello thanks for the return, this way would work but not always the string comes with this format, it may come like this 1 day 20 min.

  • Then you must change your question.

  • But then you just deal with a noose.

  • All parts " dia", " hr", " min", etc. that you know can come, you have conditions to remove space using this solution. The snippets that it does not find it does not replace. Now, if you do not know beforehand the passages that may come, you have to inform what we should expect to come so that we can suggest a regex or some other way.

  • Can do with regex also, identifying a numeric string, find remove the space after it, having so hrs , mins, seq ...

  • I included an alternative solution with regex that does not depend on the "day", "min" sequences, etc.

Show 2 more comments

2

String comEspaco = "8 hrs 2 mins";
String semEspaco;

if (comEspaco.constains("hrs")){
    semEspaco = comEspaco.replace(" hrs", "hrs").replace(" mins", "mins")
} else{
    semEspaco = comEspaco.replace(" dia", "dia").replace(" hrs", "hrs")
}
  • Thank you for the kindness @sicachester

2

One possible way is to use a Stringbuffer and use the method replace():

String hora = "8 hrs 2 mins";
int firstSpace = hora.indexOf(" ");
int lastSpace = hora.lastIndexOf(" ");
StringBuffer buf = new StringBuffer(hora);

buf.replace(firstSpace, firstSpace + 1, "");
buf.replace(lastSpace-1, lastSpace, "");//Note que após o replace anterior o buffer tem menos um caracter

System.out.println(buf.toString());

See working on Ideone

Another way using subString()

Declare a method that replaces at a given position:

public static String replaceCharAt(String s, int pos, String c) {
    return s.substring(0, pos) + c + s.substring(pos + 1);
}

Use it as follows:

String hora = "8 hrs 2 mins";
int firstSpace = hora.indexOf(" ");

String temp = replaceCharAt(hora, firstSpace, "");

int lastSpace = temp.lastIndexOf(" ");
String horaSemEspacos = replaceCharAt(temp, lastSpace, "");

System.out.println(horaSemEspacos);

See working on Ideone

  • Thank you! I did using your recommendation and it worked for all situations.

1


As you said the format can be varied ( min, mins, miNs, etc...) I will post another way of doing considering the spaces and not the words.

You can use the class Scanner for this, the staff only remembers her to do reading with System.in but it has several useful resources. Scanner#next() returns the next input token and these tokens are by default separated by spaces.

If the input format is always the one you posted, then you can use next() + next() to pick up the tokens two by two. It would look like this:

TOKENS:        8      |   hrs    |    2    |   mins

               ^           ^          ^         ^
               |           |          |         |
               |           |          |         |
CHAMADAS:    next()  +   next()  |  next()  +  next()

                     ^                      ^
                     |                      |

RESULTADO:          8hrs         |        2mins

I made a method with this logic:

public String format(String string){
   Scanner scanner = new Scanner(string);
   StringBuilder sb = new StringBuilder();
   while(scanner.hasNext())
      sb.append(scanner.next())
        .append(scanner.next())
        .append(" ");
   return sb.toString();
}

And in the tests the results were:

String test1 = "50 min";
String test2 = "20 hrs 50 mins";
String test3 = "1 d 20 hrs 50 min";
String test4 = "3 meses 15 dias 20 horas 50 minutos";

System.out.println(format(test1)); // 50min 
System.out.println(format(test2)); // 20hrs 50mins 
System.out.println(format(test3)); // 1d 20hrs 50min 
System.out.println(format(test4)); // 3meses 15dias 20horas 50minutos 

Online example

  • PS: I would choose Piovezan’s answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.