Soon
Soon

Reputation: 339

Eliminating spaces and words starting with particular chars from JAVA string

Eliminating spaces and words starting with particular chars from JAVA string.

With the following code spaces between string words are eliminated:

String str1= "This is symbel for snow and silk. Grapes are very dear"
String str2=str1.replaceAll(" ","");
System.out.println(str2);

It gives this output:-

output:
Thisissymbelforsnowandsilk.Grapesareverydear 

But I want to eliminate all the words in str1 starting with char 's' (symbel snow silk) and char 'd' (dear) to get the following output:-

output:
Thisisforand.Grapesarevery

How it can be achieved by amending this code?

Upvotes: 3

Views: 122

Answers (3)

Matt Coubrough
Matt Coubrough

Reputation: 3829

The best solution is to use a Regular Expression also known as a Regex.

These are designed specifically for complex search and replace functionality in strings.

This one:

"([sd]\\w+)|\\s+"

matches a word group indicated by the parentheses () starting with 's' or 'd' followed by one or more "word" characters (\\w = any alpha numeric or underscore) OR one or more whitespace characters (\\s = whitespace). When used as an argument to the String replaceAll function like so:

s.replaceAll("([sd]\\w+)|\\s+", "");

every occurance that matches either of these two patterns is replaced with the empty string.

There is comprehensive information on regexes in Oracle's java documentation here:

http://docs.oracle.com/javase/tutorial/essential/regex/

Although they seem cryptic at first, learning them can greatly simplify your code. Regexes are available in almost all modern languages so any knowledge you gain about regexes is useful and transferable.

Furthermore, the web is littered with handy sites where you can test your regexes out before committing them to code.

Upvotes: 3

Nambi
Nambi

Reputation: 12042

Do like this

String str1= "This is symbel for snow and silk. Grapes are very dear";
System.out.print(str1.replaceAll("[sd][a-z]+|[ ]+",""));

Explanation

Upvotes: 2

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136012

try this

s = s.replaceAll("([sd]\\w+)|\\s+", "");

Upvotes: 1

Related Questions