Hassaan Rabbani
Hassaan Rabbani

Reputation: 2465

Removing items from String

I am trying to replace all occurrences of a substring from a String.

I want to replace "\t\t\t" with "<3tabs>"
I want to replace "\t\t\t\t\t\t" with "<6tabs>"
I want to replace "\t\t\t\t" with "< >"

I am using

s = s.replace("\t\t\t\t", "<    >");
s = s.replace("\t\t\t", "<3tabs>");
s = s.replace("\t\t\t\t\t\t", "<6tabs>");

But no use, it does not replace anything, then i tried using

s = s.replaceAll("\t\t\t\t", "<    >");
s = s.replaceAll("\t\t\t", "<3tabs>");
s = s.replaceAll("\t\t\t\t\t\t", "<6tabs>");

Again, no use, it does not replace anything. after trying these two methods i tried StringBuilder

I was able to replace the items through StringBuilder, My Question is, why am i unable to replace the items directly through String from the above two commands? Is there any method from which i can directly replace items from String?

Upvotes: 1

Views: 103

Answers (3)

Ketan Ahir
Ketan Ahir

Reputation: 6748

try in this order

String s = "This\t\t\t\t\t\tis\t\t\texample\t\t\t\t";
s = s.replace("\t\t\t\t\t\t", "<6tabs>");
s = s.replace("\t\t\t\t", "<    >");
s = s.replace("\t\t\t", "<3tabs>");
System.out.print(s);

output:

This<6tabs>is<3tabs>example<    >

Upvotes: 2

Renan Bandeira
Renan Bandeira

Reputation: 3268

Take a look at this

Go through your text, divide it into a char[] array, then use a for loop to go through the individual characters. Don't print them out straight, but print them using a %x tag (or %d if you like decimal numbers).

char[] characters = myString.tocharArray();  
for (char c : characters)  
{  
   System.out.printf("%x%n", c);  
}  

Get an ASCII table and look up all the numbers for the characters, and see whether there are any \n or \f or \r. Do this before or after.

Different operating systems use different line terminating characters; this is the first reference I found from Google with "line terminator Linux Windows." It says Windows uses \r\f and Linux \f. You should find that out from your example. Obviously if you strip \n and leave \r you will still have the text break into separate lines.

You might be more successful if you write a regular expression (see this part of the Java Tutorial, etc) which includes whitespace and line terminators, and use it as a delimiter with the String.split() method, then print the individual tokens in order.

Upvotes: 0

Tim B
Tim B

Reputation: 41210

6tabs is never going to find a match as the check before it will have already replaced them with two 3tabs.

You need to start with largest match first.

Strings are immutable so you can't directly modify them, s.replace() returns a new String with the modifications present in it. You then assign that back to s though so it should work fine.

Put things in the correct order and step through it with a debugger to see what is happening.

Upvotes: 1

Related Questions