skip to Main Content

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


  1. Try concatenating substrings:

     String adana = "123456789133";
     if (adana.length() > 2 && adana.charAt(2) == '3') {
         final String newText = adana.substring(0,2) + "9" + adana.substring(3);
         Log.d("TAG", "onCreate: " + newText);
     }
    
    Login or Signup to reply.
  2. 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:

    String adana = "123456789133";
    StringBuilder newText = new StringBuilder();
    for (int i = 0; i < adana.length(); i++) {
        if (i == 2 && adana.charAt(2) == '3') {
            newText.append('9');
        } else {
            newText.append(adana.charAt(i));
        }
    }
    

    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:

    String newText = "";
    for (int i = 0; i < adana.length(); i++) {
        if (i == 2 && adana.charAt(2) == '3') {
            newText += "9";
        } else {
            newText += adana.charAt(i);
        }
    }
    
    Login or Signup to reply.
  3. You can use this:

    final String newText = adana.replaceAll("3(?<=^\d{3})", "9");
    

    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() or replaceFirst() since it accepts regex. Both case works.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search