Reputation: 52386
Can't figure out how to replace a string with a character in Java. I wanted a function like this:
replace(string, char)
but there's not a function like this in Java.
String str = str.replace("word", '\u0082');
String str = str.replace("word", (char)130);
How do I go about this?
Upvotes: 1
Views: 4048
Reputation: 316
the simplest way:
"value_".replace("_",String.valueOf((char)58 )); //return "value:"
EDIT:
(char)58 //return: ':'
(int)':' //return: 58
Since we want to work with codes and no character we have to pass code to character
another problem to solve is that method "replace" does not take "(String x,char y)"
So we pass our character to String this way:
String.valueOf((char)58) //this is a String like this ":"
Finally we have String from int code, to be replaced.
Upvotes: 0
Reputation: 1753
"String is a sequence of characters"
String s="hello";
char c='Y';
System.out.println(s.replace(s, Character.toString(c)));
Output:
Y
Upvotes: 0
Reputation: 106
You asked for a "function"
in Java, you can allways create a method
like this
public static String replace (String text, char old, char n){
return text.replace(old, n);
}
Then you can call this method
as you want
String a = replace("ae", 'e', '3');
In this case the method
will return a String
with a3
as value, but you can replace not only a char
by another, you can replace a String
with multiple characters in the same way
public static String replace (String text, String old, String n){
return text.replace(old, n);
}
Then you call this method
like this
String a = replace("aes", "es", "rmy");
The result will be a String
with army
as value
Upvotes: 1
Reputation: 4555
Very simply:
String orginal = "asdf";
char replacement = 'z';
orginal = original.replace(original, replacement+"");
Upvotes: 1
Reputation: 4102
Use a string as the replacement that happens to be only a single character in length:
String original = "words";
String replaced = original.replace("word", "\u0130");
The replaced
instance will be equivalent to "İs".
Note also that, from your question, '\u0130'
and (char)130
are not the same characters. The \u
syntax uses hexadecimal and your cast is using decimal notation.
Upvotes: 1