Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Changing Part of String with Specific Character [closed]

I am trying to take a part of a String from point(a,b) and replace letters from given values in the string into 'X's.

Example: If the string is ABC123 and switch(3,5) is called, it would change it to ABCXXX.

So far I have:

  public void switch(int p1, int p2)
{
   String substring = myCode.substring(p1,p2-1);
}

I am very lost....thanks for any help!

like image 409
user1729448 Avatar asked Nov 24 '22 13:11

user1729448


2 Answers

Java Strings are immutable and can not be changed. You could however, write a method that returns a new String with those characters marked out. A StringBuilder is a good class to familiarize yourself with as it allows for fast string manipulations.

StringBuilder documentation: http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html

public class StringReplace {

    public static String replaceRange(String s, int start, int end){
        StringBuilder b = new StringBuilder(s);

        for(int i = start; i <= end; i++)
            b.setCharAt(i, 'x');

        return b.toString();
    }

    public static void main(String[] args){
        String test = "mystringtoreplace";
        String replaced = replaceRange(test, 3, 8);
        System.out.println(replaced);
    }

}
like image 180
Joe Avatar answered Dec 05 '22 03:12

Joe


Use StringBuilder and its replace(int start, int end, String str) method

like image 23
Ioan Avatar answered Dec 05 '22 04:12

Ioan