what I want to do is to replace it with 9 if 3 is written in the 3rd character in a data. But I only want to do this for the 3rd character. How can I do it? This code I wrote replaces all 3’s in the string with 9.
Regards…
String adana = "123456789133";
if (adana.length() > 2 && adana.charAt(2) == '3'){
final String newText = adana.replace("3", "9");
Log.d("TAG", "onCreate: " + newText);
}
3
Answers
Try concatenating substrings:
Your code checks relatively correctly, however you are failing to actually do the replacement. When using the
replace()
method of a string what java will do is replace all occurrences passed as the first parameter with the value passed in the second parameter. So naturally what you are talking about will happen. One way to solve this in this specific case is to do:This strategy will work for any string of any length.
Or if you don’t want to use string builders (which is not recommended in this case), you can do:
You can use this:
The regex I used here uses positive look behind to search for occurrence of 3 in the 3rd position of the string. You can use
replaceAll()
orreplaceFirst()
since it accepts regex. Both case works.