Home > Back-end >  Inserting char at a specific position in a String
Inserting char at a specific position in a String

Time:07-11

I am writing a function to add a backslash after every backslash in a string, for example, I want a string like this "C:\Users\acer\Desktop\Test.docx" to turn into this "C:\\Users\\acer\\Desktop\\Test.docx", but for some reason, I can't add backslashes anywhere except after the final backslash in the text.

   public static String validate(String text) {
    String t = text;
    String t1 = "";
    for (int i = 0; i < t.length(); i  ) {
        if (t.charAt(i) == '\\') {
            t1 = t.substring(0, i)   "\\"   t.substring(i);
        }
    }
    t = t1;
    return t;
}

the output is the following: "C:\Users\acer\Desktop\\\Test.docx"

(used "C:\Users\acer\Desktop\Test.docx" as an example)

CodePudding user response:

With this simple code your problem should be solved, without using any loop.

public class Main {
    public static void main( String[] args ) {
        String path_singleSlash = "C:\\Users\\acer\\Desktop\\Test.docx";

        String path_doubleSlash = path_singleSlash.replaceAll( "\\\\", "\\\\\\\\" );

        System.out.println( "Single slash: "   path_singleSlash );
        System.out.println( "Double slash: "   path_doubleSlash );
    }
}

Output:

Single slash: C:\Users\acer\Desktop\Test.docx
Double slash: C:\\Users\\acer\\Desktop\\Test.docx

Let me know if it was helpful.

  • Related