1

I was trying to use StringBuilder to replace my char at 'x' index for "null".. So, let's suppose my input for 'mine' is "<><><>", but I want to replace the index 2(<) and 3(>) for "null", so I would get as output "<><>". The problem is, apparently I can't leave the second argument of sb.setCharAt(2, ''); as '',because I get an error message, so I was wondering what I could do to get the desired output

Scanner sc = new Scanner(System.in);

String mine = sc.next();

StringBuilder sb = new StringBuilder(mine);
sb.setCharAt(2, '');
sb.setCharAt(3, '');
mine = sb.toString();

System.out.println(mine);
4
  • 3
    How about sb.deleteCharAt(2); Commented May 16, 2020 at 16:13
  • 1
    char is a primitive, so what exactly is a null char ? Commented May 16, 2020 at 16:17
  • 2
    deleteChatAt actually worked, thank you man!!! I'm new to programming so I didn't know this method Commented May 16, 2020 at 16:20
  • According to How many classes are there in Java standard edition? there are almost 4,500 classes in JDK 12. Now think how many methods there are. I doubt there is a person who knows them all. That's why there is that thing called javadoc, so you can see what methods exist in class StringBuilder, for example. Commented May 16, 2020 at 16:28

3 Answers 3

1

It is showing error as '' not a char, 'no character' is not a valid char.

You can use StringBuilder#delete for that :

StringBuilder sb = new StringBuilder("<><><>");
sb.delete(2, 4);
System.out.println(sb);

If you use StringBuilder#deleteCharAt then keep in mind that index changed after invoking the method. For your case you have to delete the char from index 2 consecutively.

StringBuilder sb = new StringBuilder("<><><>");
sb.deleteCharAt(2);
sb.deleteCharAt(2);
System.out.println(sb);
Sign up to request clarification or add additional context in comments.

Comments

1

You can't insert an empty character. you need to use deleteCharAt(index) or delete(startIndex,endIndex)- end index not included.

forEx-

String mine="<><><>";
StringBuilder sb = new StringBuilder(mine);
sb.deleteCharAt(2);
sb.deleteCharAt(2);
mine = sb.toString();
System.out.println(mine);

This would give output <><>

Comments

1

You can do it using the String builder's deleteCharAt(int index) method. But remember that at each call it will modify the string, so you need to call it twice with the same index. Something like this:

Scanner sc = new Scanner(System.in);

        String mine = sc.next();
        StringBuilder sb = new StringBuilder(mine);
        sb.deleteCharAt(2);
        sb.deleteCharAt(2);
        System.out.println(sb.toString());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.