Reputation: 23
I have a string, with characters a-z
, A-Z
, 0-9
, (
, )
, +
, -
, etc.
I want to find every word within that string and replace it with the same word with 'word'
(single quotes added). Words in that string can be preceded/followed by "(", ")", and spaces.
How do I go about doing that?
Input:
(Movie + 2000)
Output:
('Movie' + '2000')
Upvotes: 2
Views: 8278
Reputation: 1
It makes sense to return string only if a replacement took place, see below:
if(s>0)
return result.toString();
else
return null;
Upvotes: 0
Reputation: 19177
As stated in the comments, regex is a good way to go:
String input = "(Movie + 2000)";
input = input.replaceAll("[A-Za-z0-9]+", "'$0'");
You don't give a precise defition of 'word', so I assume it is any combination of letters and numbers.
EDIT OK, thanks to @Buhb for explaining why this solution is not the best one. Better solution was given by @Bohemian.
Upvotes: 0
Reputation: 425033
Keep it simple! This does what you need:
String input = "(Movie + 2000)";
input.replaceAll("\\b", "'");
// Outputs "('Movie' + '2000')"
This uses the regex \b
, which is a "word boundary". What could be simpler?
Upvotes: 7
Reputation: 5456
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
String str1 = "Hello string";
String str2 = "str";
System.out.println(replace(str1, str2, "'" + str2 + "'"));
}
static String replace(String str, String pattern, String replace) {
int s = 0;
int e = 0;
StringBuffer result = new StringBuffer();
while ((e = str.indexOf(pattern, s)) >= 0) {
result.append(str.substring(s, e));
result.append(replace);
s = e + pattern.length();
}
result.append(str.substring(s));
return result.toString();
}
}
Output: Hello 'str'ing
WBR
Upvotes: 0