因此,如果您要添加字符串,则可以通过+=
方法(我知道并使用atm)添加它们。但是如何删除字符串/字符串数组中的单词?
示例:我有一个字符串
String="Monday,Tuesday,Wednesday"
如何进入
String="Monday,Wednesday"
有什么帮助吗?
答案 0 :(得分:1)
简单
只需使用
yourString = yourString.replaceAll("the text to replace", ""); //the second "" show empty string so the text will get replace by empty string
最后你的字符串将包含你想要的文本:)
答案 1 :(得分:1)
您可以使用replace方法。
String sentence = "Monday,Tuesday,Wednesday";
String replaced = sentence.replace("Tuesday,", "");
答案 2 :(得分:0)
您可以使用"公共字符串替换(char oldChar,char newChar)"方法,如果你想删除"星期二"而不是第二个元素
https://stackoverflow.com/questions/16702357/how-to-replace-a-substring-of-a-string
答案 3 :(得分:0)
我认为,我会将其用于简单,否则请转到其他建议的答案......
使用Arraylist存储天数:
ArrayList<String> days = new ArrayList<String>();
days.add("Monday");
days.add("Tuesday");
days.add("Wednesday");
用它来创建天数字符串:
public String getDays() {
String daysString = "";
for (int i = 0; i < days.size(); i++) {
if (i != 0)
daysString += ", ";
daysString += days.get(i);
}
return daysString;
}
无论何时你想删除使用
days.remove(1);
或
days.remove("Tuesday");
然后再次致电getDays();
IInd方法如果您只想使用字符串:
String list = "Monday,Tuesday,Wednesday";
System.out.println("New String : " + removeAtIndex(list, 1));
和
public String removeAtIndex(String string, int index) {
int currentPointer = 0;
int lastPointer = string.indexOf(",");
while (index != 0) {
currentPointer = string.indexOf(',', currentPointer) + 1;
lastPointer = string.indexOf(',', lastPointer + 1);
index--;
}
String subString = string.substring(currentPointer,
lastPointer == -1 ? string.length() : lastPointer);
return string.replace((currentPointer != 0 ? "," : "") + subString
+ (currentPointer == 0 ? "," : ""), "");
}
答案 4 :(得分:0)
使用正则表达式这样的东西:
String contents = "Monday,Tuesday,Wednesday";
contents = contents.replaceAll("[\\,]+Tuesday|^Tuesday[\\,]*", "");