Reputation: 1179
I have a file and i converted that file into string. Now whenever i am trying to replace some camelcase data like 'fooBar' with lowercase data like 'foobar' then it is not working.
I tried these 2 cases.
String target = "fooBar and tooohh";
target = target.replace("foobar", "");
System.out.println(target);
Its giving me this output fooBar and tooohh
Then I tried this
String target123 = "fooBar and tooohh";
target123=target123.replace("(?i)foobar", "") ;
System.out.println(target123);
and this also giving me same output : - fooBar and tooohh
Upvotes: 0
Views: 125
Reputation: 870
You are replacing the string "foobar" which is not in "fooBar and tooohh". replace is case sensitive, so if you would want to replace "fooBar" with "" (nothing), you'd use:
string target = "fooBar and tooohh";
target = target.replace("fooBar", "");
This would return:
" and tooohh"
However, you've asked to lowercase all the camelcased words in which case you would do this:
string target = "fooBar and tooohh";
target = target.toLowerCase();
returns:
"foobar and tooohh"
Upvotes: 1
Reputation: 29703
Use String::replaceAll or String::replaceFirst method and regex (?i)foobar
String replaced = target.replaceAll("(?i)foobar", "");
or
String replaced = target.replaceFirst("(?i)foobar", "");
Method String::replace
cann't be used with regex
Upvotes: 2
Reputation: 7133
As told by other String is immutable so you need to reassigne.
target = target.replace("foobar", "");
With String.replaceAll you can use a regex so for your needs:
target = target.replaceAll("(?i)foobar", "");
If you want to set all the string to lowercase then use String.toLowerCase
target = target.toLowerCase();
Upvotes: 1
Reputation: 54722
Just use String.toLowerCase method
So if you want to make whole string lower case you can do like
String result = test.toLowerCase();
Now if you only want to make the fooBar to lower case you can do somethinglike
String temp = "fooBar";
String result = test.replace(temp,temp.toLowerCase());
[Just tried to give a concept]
Upvotes: 1
Reputation: 738
It is because String
is immutable in java, so if you want to change a String
with replace()
method you have to reassigne your variable like this:
target = target.replace("foobar", "");
Upvotes: 0