Search code examples
javastringreplacestring-lengthreplaceall

String length after replacing a string in Java?


How can I get the correct length of the new string after replacing a substring in the string. I used the string length and got the length of 1st string. ie. My string is "abcdefg" and length is 7. After replacing "cde" with "z", the new string is abzfg ( by using replace all) and the length of new string is still 7, if I use string length. Can I get the correct length 5 by any method?


Solution

  • String are immutable in Java. You can't change them.

    You will need to use another String or use StringBuilder.

    String A = "abcdefg";
    String B = A.substring(0,2) + 'z' + A.substring(5,6);
    

    Or With StringBuilder

    StringBuilder A = new StringBuilder("abcdefg");
    A.replace(2,5,"z");