+ 1

How do i get rid of a character if i know its position in a java string?

1st Nov 2017, 2:35 AM
William Rodriguez
William Rodriguez - avatar
3 Respostas
+ 17
E.g. public static String str_del_dex(String str, int del_dex) { return str.substring(0, del_dex) + str.substring(del_dex+1, str.length()); } // later in main String str = "Hello World"; // we want to remove the space, which is at index 5. str = str_del_dex(str, 5); System.out.print(str);
1st Nov 2017, 2:43 AM
Hatsy Rei
Hatsy Rei - avatar
+ 4
You can use StringBuilder/StringBuffer and then use the deleteCharAt(index) method. String s = "string"; StringBuilder sb = new StringBuilder(s); sb.deleteCharAt(2); s = sb.toString(); // s now equals "sting"
1st Nov 2017, 3:45 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
public class Program { public static void main(String[] args) { String s = "a string of letters"; int letterPosition = 5; //i String textBefore = s.substring(0, letterPosition-1); String textAfter = s.substring(letterPosition, s.length()); System.out.println(textBefore + textAfter); } }
1st Nov 2017, 6:54 PM
DaveW