This question already has answers here:
Replace a character at a specific index in a string?
(9 answers)
Closed 7 years ago.
I am trying to replace a character at a specific position of a string.
For example:
String str = "hi";
replace string position #2 (i) to another letter "k"
How would I do this?
Thanks!
Petar Ivanov's answer to replace a character at a specific index in a string question
String are immutable in Java. You can't change them.
You need to create a new string with the character replaced.
String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);
Or you can use a StringBuilder:
StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');
System.out.println(myName);
Kay!First of all, when dealing with strings you have to refer to their positions in 0 base convention. This means that if you have a string like this:
String str = "hi";
//str length is equal 2 but the character
//'h' is in the position 0 and character 'i' is in the postion 1
With that in mind, the best way to tackle this problem is creating a method to replace a character at a given position in a string like this:
Method:
public String changeCharInPosition(int position, char ch, String str){
char[] charArray = str.toCharArray();
charArray[position] = ch;
return new String(charArray);
}
Then you should call the method 'changeCharInPosition' in this way:
String str = "hi";
str = changeCharInPosition(1, 'k', str);
System.out.print(str); //this will return "hk"
If you have any questions, don't hesitate, post something!
Use StringBuilder:
StringBuilder sb = new StringBuilder(str);
sb.setCharAt(i - 1, 'k');
str = sb.toString();
To replace a character at a specified position :
public static String replaceCharAt(String s, int pos, char c) {
return s.substring(0,pos) + c + s.substring(pos+1);
}
If you need to re-use a string, then use StringBuffer:
String str = "hi";
StringBuffer sb = new StringBuffer(str);
while (...) {
sb.setCharAt(1, 'k');
}
EDIT:
Note that StringBuffer is thread-safe, while using StringBuilder is faster, but not thread-safe.
Related
i am trying to replace all occurrences of the first character in a string with another using the replace all function. However, no change occurs when i run the function. I tried to target the first character of the original string and then carry the out the replacement but no luck. Below is a snippet of my code.
public static String charChangeAt(String str, String str2) {
//str = x.xy
//str2 = d.w
String res = str.replaceAll(Character.toString(str.charAt(0)), str2);
return res ;
}
Your code replaces all characters that match the first character. If your string is abcda and you run your function, it will replace all occurences of a with whatever you put. Including the last one.
To achieve your goal you should probably not use replaceAll.
You could use StringBuilder.
StringBuilder builder = new StringBuilder(str);
myName.setCharAt(0, str2.charAt(0));
In case you want to replace all occurrences of the first character in a string with another, you can use replace instead of replaceAll. Below is the code snippet.
String str = "x.xy";
String str2 = "d.w";
String res = str.replace(Character.toString(str.charAt(0)), str2);
return res; // will output d.w.d.wy
Your function works fine but you probably are using it the wrong way.
For these strings:
String str = "abaca";
String str2 = "x";
if you do:
charChangeAt(str, str2);
this will not affect str.
You must assign the value returned by your function to str:
str = charChangeAt(str, str2);
This will change the value of str to:
"xbxcx"
I am trying to replace only one character of a string. But whenever the character has multiple occurrences within the string, all of those characters are being replaced, while I only want the particular character to be replaced. For example:
String str = "hello world";
str = str.replace(str.charAt(2), Character.toUpperCase(str.charAt(2)));
System.out.println(str);
Gives the result:
heLLo worLd
while I want it to be:
heLlo world
What can I do to achieve this?
replace will not work because it replace all the occurrence in the string. Also replaceFirst will not work as it will always remove
the first occurrence.
As Strings are non mutable , so in either way you need create a new string always. Can be done by either of the following.
Use substring, and manually create the string that you want.
int place = 2;
str = str.substring(0,place)+Character.toUpperCase(str.charAt(place))+str.substring(place+1);
Convert the string to array of characters and replace any character that you want by using index, and then convert array back to the string.
You should use a StringBuilder instead of String to achieve this goal.
This code works too
String str = "hello world";
str = str.replaceFirst(String.valueOf(str.charAt(2)),
String.valueOf(Character.toUpperCase(str.charAt(2))));
System.out.println(str);
String str = "hello world";
char[] charArray = str.toCharArray();
charArray[2] = Character.toUpperCase(charArray[2]);
str = new String(charArray);
System.out.println(str);
replace(char, char) will replace all occurrences of the specified char, not only the char at the index. From the documentation
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
You can do something like
String str = "hello world";
String newStr = str.substring(0, 2) + Character.toUpperCase(str.charAt(2)) + str.substring(3);
I want to replace all numbers inside a string with specific values.
Teststring: -SD12431;ABC333
How can I identify blocks of digits, and especially replace them with a (dynamic) new value?
For example after replacement:
-SDfirst;ABCsecond?
The replaceFirst() method will let you do this if you use it in a loop.
String myNewString = myString.replaceFirst("\\d+","first");
If you loop over the this statement, each invocation of replaceFirst() will replace the first group of digits with whatever you provide as a second argument.
You can do it this way
StringBuffer sb = new StringBuffer();
Matcher m = Pattern.compile("\\d+").matcher(str);
int n = 0;
while(m.find()) {
if (++n == 1) {
m.appendReplacement(sb, "first");
} else {
m.appendReplacement(sb, "second");
}
}
m.appendTail(sb);
s = sb.toString();
You can do something like this:
yourString = yourString.replaceFirst("\\d+",firstString).replaceFirst("\\d+",secondString); //and so on
or use a loop if it fits your needs better
You can use the replaceFirst(String regex, String replacement) function of the string class.
Look at
http://javarevisited.blogspot.fr/2011/12/java-string-replace-example-tutorial.html
So in first argument you have to use a regex for finding digit such as :
"[0-9]" will find a single digit
"[0-9]+" will find one or more digit
String testString = "-SD12431;ABC333";
ArrayList<String> remplaceBy= new ArrayList<String>();
remplaceBy.add("first");
remplaceBy.add("second");
remplaceBy.add("third");
String newString = testString;
String oldString ="";
int i =0;
while(!newString.equals(oldString))
{
oldString = new String(newString);
newString = newString.replaceFirst("[0-9]+",remplaceBy.get(i));
i++;
System.out.println("N1:"+newString);
System.out.println("O1:"+oldString);
}
System.out.println("New String"+newString);
This question already has answers here:
How to separate specific elements in string java
(3 answers)
Closed 9 years ago.
so the method takes two parameters, first is the String you will be splitting, second is the delimiter(where to split at).
So if I pass in "abc|def" as the first parameter and "|" as the second I should get a List that returns "abc, def" the problem I'm having is that my if statement requires the delimiter is in the current string to be accessed. I can't think of a better condition, any help?
public List<String> splitIt(String string, String delimiter){
//create and init arraylist.
List<String> list = new ArrayList<String>();
//create and init newString.
String newString="";
//add string to arraylist 'list'.
list.add(string);
//loops through string.
for(int i=0;i<string.length();i++){
newString += string.charAt(i);
if(newString.contains(delimiter)){
//list.remove(string);
list.add(newString.replace(delimiter, ""));
newString="";
}
}
return list;
}
Badshaah and cmvaxter code for split using builtin function split(regex) won't work. as you pass "|" as a delimiter "sam|ple" it wont be splitted as [sam,ple] because ( | , + , * , ...) are all used in regex for other purposes.
and u can check character by character, if the delimiter is a character
loop(each char)
if(not delim)
append to list[i]
else
increment i, discard char
learning purpose it might be needed in c or c++ (even they 've strtok to split strings) to improve effeciency or to modify something differently. [may split differently not using regex]
Its best to use existing system libraries and functions.
if u want to use your function do something like
write these functions yourself
findpos(delim) // gives position of delimiter found in string
substring(pos,len) //len:size of delimiter
getlist(String str,String delim)
//for each delim found use substring and append to list
use some pattern matching algorithms like KMP or something u know.
Change your whole method to.
public List<String> splitIt(String string, String delimiter){
String[] out = string.split(delimiter);
return Arrays.asList(out);
}
Since you are iterating through the string, your if should be based on the character you are inspecting, instead of invoking contains each time:
public List<String> splitIt(String string, String delimiter){
//create and init arraylist.
List<String> list = new ArrayList<String>();
//create and init newString.
String newString="";
//add string to arraylist 'list'.
list.add(string);
//loops through string.
int lastDelimiter = 0;
for (int i=0; i<string.length(); i++) {
if (delimiter.equals("" + string.charAt(i))) {
list.add(string.substring(lastDelimiter, i));
lastDelimiter = i + 1;
}
}
if (lastDelimiter != string.length())
list.add(string.substring(lastDelimiter, string.length()));
return list;
}
For the sake of learning, I think your original attempt lends itself to a recursive solution. The general idea in this case would be:
If there are no delimiters in the string and it is not empty, return the string as the only element in a new list
Otherwise
find the first occurrence of the delimiter
extract the string from the beginning up to the delimiter, call it 'found'
remove the delimiter
recursively call this method, passing it the remainder of the string and the delimiter
append 'found' to the list returned from #4, and return that list
The String class already supports a split method that I believe does exactly what you are looking to do.
String[] s = "abc|def".split("\\|");
List<String> list = Arrays.asList(s);
If you want to do it yourself, the code might look something like this:
char delim = "|".charAt(0);
String s = "abc|def|ghi";
char[] chars = s.toCharArray();
StringBuilder sb = new StringBuilder();
List<String> list = new ArrayList<String>();
for(char c: chars){
if (c == delim){
list.add(sb.toString());
sb = new StringBuilder();
}
else{
sb.append(c);
}
}
if (sb.length() > 0) list.add(sb.toString());
System.out.println(list);
I know of no easy way to do this. Suppose I have the following string-
"abcdefgh"
I want to get a string by replacing the third character 'c' with 'x'.
The long way out is this -
s1 = substring before third character = "ab" in this case
s2 = new character = "x" in this case
s3 = substring after third character = "defgh" in this case
finalString = s1 + s2 + s3
Is there a simpler way? There should be some function like
public String replace(int pos, char replacement)
Use StringBuilder#replace().
StringBuilder sb = new StringBuilder("abcdefgh");
sb.replace(2, 3, "x");
String output = sb.toString();
http://ideone.com/Tg5ut
You can convert the String to a char[] and then replace the character. Then convert the char[] back to a String.
String s = "asdf";
char[] arr = s.toCharArray();
arr[0] = 'b';
s = new String(arr);
No. There is no simpler way than to concatenate the pieces.
Try using a StringBuilder instead StringBuilder Java Page
Since every String is basically just a char[] anyway, you could just grab it and manipulate the individual chars that way.
Try the String.replace(Char oldChar, Char newChar) method or use a StringBuilder
How about:
String crap = "crap";
String replaced = crap.replace(crap.charAt(index), newchar);
but this will replace all instances of that character
String yourString = "abcdef"
String newString = yourString.replaceAll("c" , "x");
System.out.println("This is the replaced String: " + newString);
This is the replaced String: abxdef