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);
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 have a String which contains data separated by comma (,) for each value. I wanna replace comma by some other delimiter. But need to replace comma alternatively.
That means second, forth, sixth occurrence of comma need to be replaced. Is there any possible way to do?
Eg: "a,b,c,d,e,f" is the string available and want the output as "a,b c,d e,f".
You can use some regex with replaceAll like this :
String str = "a,b,c,d,e,f";
String delimiter = " ";//You can use any delimiter i use space in your case
str = str.replaceAll("([a-zA-Z]+,[a-zA-Z]+)(,)", "$1" + delimiter);
System.out.println(str);
result
a,b c,d e,f
regex demo
Here is a simple code that uses array of characters to do the task.
public class ReplaceAlternateCommas {
public static void main(String[] args) {
String str = "a,bg,dfg,d,v";
System.out.println(str);
char[] charArray = str.toCharArray();
int commaCount=0;
char replacementChar = ' ';//replace comma with this character
for(int i=0;i<charArray.length;i++){
char ch = charArray[i];
if(ch==','){
commaCount++;
if(commaCount%2==0){
charArray[i]=replacementChar;
}
}
}
str = new String(charArray);
System.out.println(str);
}
}
If you dont want to use character array you can use regex or StringBuilder .
In my application I am trying to make breadcrumbs using StringBuilder
Suppose this is the string :
String1>String2>String3>String4>String5>
Now I want to remove String5> and I want string like this:
String1>String2>String3>String4>
How can I do this?
Please help!!
you can use regex \\w+>$
\\w+ mean match [a-zA-Z0-9_]
>$ match > character where $ mean at the end
Regex Demo Link
String s = "String1>String2>String3>String4>String5>";
String s2 = s.replaceAll("\\w+>$","");
System.out.println(s2);
Output :
String1>String2>String3>String4>
Note : To avoid _ use
String s2 = s.replaceAll("[a-zA-Z\\d]+>$","");
Just in case if you have data with some special characters like
String s = "String1>Stri$#$ng2>String3>Stri#$$#ng4>St$#:/|ring5>";
then above solution won't work so you can use
String s2 = s.replaceAll("[^>]+>$","");
// s2 will be = String1>Stri$#$ng2>String3>Stri#$$#ng4>
Regex Demo Link
[^>]+ : ^ inside [] works as negation mean match everything except > character
Split string by > and then apply for loop on the array. match string by position. if match then delete otherwise add to new stringBuilder.
You can use combination of lastIndexOf and substring().
Example:
String oldValue = "String1>String2>String3>String4>String5>";
int lastIndex = oldValue.lastIndexOf('>', oldValue.length() - 2);
String newValue = oldValue.substring(0, lastIndex + 1);
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
In Java, I have a String:
Jamaica
I would like to remove the first character of the string and then return amaica
How would I do this?
const str = "Jamaica".substring(1)
console.log(str)
Use the substring() function with an argument of 1 to get the substring from position 1 (after the first character) to the end of the string (leaving the second argument out defaults to the full length of the string).
public String removeFirstChar(String s){
return s.substring(1);
}
In Java, remove leading character only if it is a certain character
Use the Java ternary operator to quickly check if your character is there before removing it. This strips the leading character only if it exists, if passed a blank string, return blankstring.
String header = "";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);
header = "foobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);
header = "#moobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);
Prints:
blankstring
foobar
moobar
Java, remove all the instances of a character anywhere in a string:
String a = "Cool";
a = a.replace("o","");
//variable 'a' contains the string "Cl"
Java, remove the first instance of a character anywhere in a string:
String b = "Cool";
b = b.replaceFirst("o","");
//variable 'b' contains the string "Col"
Use substring() and give the number of characters that you want to trim from front.
String value = "Jamaica";
value = value.substring(1);
Answer: "amaica"
You can use the substring method of the String class that takes only the beginning index and returns the substring that begins with the character at the specified index and extending to the end of the string.
String str = "Jamaica";
str = str.substring(1);
substring() method returns a new String that contains a subsequence of characters currently contained in this sequence.
The substring begins at the specified start and extends to the character at index end - 1.
It has two forms. The first is
String substring(int FirstIndex)
Here, FirstIndex specifies the index at which the substring will
begin. This form returns a copy of the substring that begins at
FirstIndex and runs to the end of the invoking string.
String substring(int FirstIndex, int endIndex)
Here, FirstIndex specifies the beginning index, and endIndex specifies
the stopping point. The string returned contains all the characters
from the beginning index, up to, but not including, the ending index.
Example
String str = "Amiyo";
// prints substring from index 3
System.out.println("substring is = " + str.substring(3)); // Output 'yo'
you can do like this:
String str = "Jamaica";
str = str.substring(1, title.length());
return str;
or in general:
public String removeFirstChar(String str){
return str.substring(1, title.length());
}
public String removeFirst(String input)
{
return input.substring(1);
}
The key thing to understand in Java is that Strings are immutable -- you can't change them. So it makes no sense to speak of 'removing a character from a string'. Instead, you make a NEW string with just the characters you want. The other posts in this question give you a variety of ways of doing that, but its important to understand that these don't change the original string in any way. Any references you have to the old string will continue to refer to the old string (unless you change them to refer to a different string) and will not be affected by the newly created string.
This has a number of implications for performance. Each time you are 'modifying' a string, you are actually creating a new string with all the overhead implied (memory allocation and garbage collection). So if you want to make a series of modifications to a string and care only about the final result (the intermediate strings will be dead as soon as you 'modify' them), it may make more sense to use a StringBuilder or StringBuffer instead.
I came across a situation where I had to remove not only the first character (if it was a #, but the first set of characters.
String myString = ###Hello World could be the starting point, but I would only want to keep the Hello World. this could be done as following.
while (myString.charAt(0) == '#') { // Remove all the # chars in front of the real string
myString = myString.substring(1, myString.length());
}
For OP's case, replace while with if and it works aswell.
You can simply use substring().
String myString = "Jamaica"
String myStringWithoutJ = myString.substring(1)
The index in the method indicates from where we are getting the result string, in this case we are getting it after the first position because we dont want that "J" in "Jamaica".
Another solution, you can solve your problem using replaceAll with some regex ^.{1} (regex demo) for example :
String str = "Jamaica";
int nbr = 1;
str = str.replaceAll("^.{" + nbr + "}", "");//Output = amaica
My version of removing leading chars, one or multiple. For example, String str1 = "01234", when removing leading '0', result will be "1234". For a String str2 = "000123" result will be again "123". And for String str3 = "000" result will be empty string: "". Such functionality is often useful when converting numeric strings into numbers.The advantage of this solution compared with regex (replaceAll(...)) is that this one is much faster. This is important when processing large number of Strings.
public static String removeLeadingChar(String str, char ch) {
int idx = 0;
while ((idx < str.length()) && (str.charAt(idx) == ch))
idx++;
return str.substring(idx);
}
##KOTLIN
#Its working fine.
tv.doOnTextChanged { text: CharSequence?, start, count, after ->
val length = text.toString().length
if (length==1 && text!!.startsWith(" ")) {
tv?.setText("")
}
}