-6

How can I remove multiple characters by their index from a string. I thought to use StringBuilder's deleteCharAt function. But if I delete char one by one, I will not keep track the right index. For example :

String test = "0123456789"
int[] removingIndice  = int[] {2, 4, 0};
// remove character from string
// result = "1356789"
MC X
  • 337
  • 4
  • 16
  • **1.** What have you tried ? **2.** `String` are immutable, you can't remove anything from it. **3.** See [ask] – AxelH Aug 28 '17 at 06:26
  • I know string are immutable. I was thing to use StringBuilder. – MC X Aug 28 '17 at 06:34
  • 2
    Then do it... You got downvoted because you just thought to use it without trying. You already know `StringBuilder`, so what is the question/problem ? – AxelH Aug 28 '17 at 06:36
  • https://ideone.com/xXZv0O – Jared Rummler Aug 28 '17 at 06:42
  • @zxue I figured out what you are trying to do. If you delete character by character, you loose the actual index position initially assigned for deletion and initial inputs are important especially if there are multiple same characters in the string. I'm trying for a solution, will leave ideone link here if I get desired output. – Rahul Raj Aug 28 '17 at 06:50
  • Checkout this: https://ideone.com/w8PXxg This should answer your question :) – Rahul Raj Aug 28 '17 at 07:04
  • FYI @RahulRaj **1** read the sorted list backward. **2** You can use `Arrays.asList(removingIndex)` to get a list easier. **3**, You want to remove character at specific index, not every corresponding value. **4** See [this ideone](https://ideone.com/ZI7M16) for your logic – AxelH Aug 28 '17 at 07:29
  • @AxelH Yes, I'm aware about `StringBuilder ` , just made a different way of doing. – Rahul Raj Aug 28 '17 at 11:25
  • @RahulRaj Thanks! I think that is what I am looking for. – MC X Aug 29 '17 at 13:16
  • Glad to hear the logic is worked, cheers :) – Rahul Raj Aug 29 '17 at 13:19

3 Answers3

3

Create a new string builder, iterate on string, add elements to builder if its index not in the array

StringBuilder sb = new StringBuilder("");
for(int i = 0; i< test.length; i++){
    if( !ArrayUtils.contains(removingIndice, i))
    {
        sb.append(test.charAt(i));
    }
}
test = sb.toString();
Kemal Duran
  • 1,478
  • 1
  • 13
  • 19
-1

String is immutable in Java, so you will need to create a new String with characters at positions 0,2,4 removed. As one option, you may use StringBuilder for that, as answered here: How to remove single character from a String

Mikhail
  • 844
  • 8
  • 18
-2
  1. I think, you need to redesign the task: "new string must contains all characters except ..."
  2. Now, seems weak initial data structure and the goal.