user2318101
user2318101

Reputation: 39

Replacing a character in a string when it is single

Using java how can I replace a character in a string ONLY when it occurs single?

ex:
Replace single * with a #

input string:

a*b**c*d***e  

output string:

a#b**c#d***e  

inputString.replaceAll("*", "#"); replaces all the *s and returns a#b##c#d###e

Upvotes: 2

Views: 137

Answers (2)

Mark Peters
Mark Peters

Reputation: 81054

You can use negative lookahead and lookbehind:

String s = "a*b**c*d***e";
String r = s.replaceAll("(?<!\\*)\\*(?!\\*)", "#"); // a#b**c#d***e

This reads: "an * not preceeded by an * and not followed by an *" (note the fact that * must be escaped in a regular expression, as it is a meta character).

Upvotes: 5

user2277872
user2277872

Reputation: 2973

Try using the charAt(n) method, setting the number n (the parameter) as the number of the * single ones, and then set the string to the "#" and see if that helps.

Upvotes: -1

Related Questions