如何在Java中从特定字符串中删除特定字符?
例如,我从一个文本文件中提取一个文本字符串,我需要这些单词来形成一个数组。然而,当我做所有这些时,有些单词以逗号(,)或句号(.)结尾,甚至连括号都附在它们后面(这是完全正常的)如何在Java中从特定字符串中删除特定字符?,java,string,immutability,Java,String,Immutability,例如,我从一个文本文件中提取一个文本字符串,我需要这些单词来形成一个数组。然而,当我做所有这些时,有些单词以逗号(,)或句号(.)结尾,甚至连括号都附在它们后面(这是完全正常的) 我想做的是摆脱那些角色。我一直在尝试使用Java中预定义的字符串方法来实现这一点,但我就是绕不过去。您不能在Java中修改字符串。它们是不变的。您所能做的就是创建一个新字符串,它是旧字符串的子字符串,减去最后一个字符 在某些情况下,StringBuffer可能会对您有所帮助。将变量重新分配给子字符串: s = s.su
我想做的是摆脱那些角色。我一直在尝试使用Java中预定义的字符串方法来实现这一点,但我就是绕不过去。您不能在Java中修改字符串。它们是不变的。您所能做的就是创建一个新字符串,它是旧字符串的子字符串,减去最后一个字符
在某些情况下,StringBuffer可能会对您有所帮助。将变量重新分配给子字符串:
s = s.substring(0, s.length() - 1)
也是解决问题的另一种方法:您可能还想考虑使用A来读取文件并将分隔符设置为您不想成为单词的一部分。
< P>使用:String str = "whatever";
str = str.replaceAll("[,.]", "");
需要一段时间。这:
…查找每个逗号和/或句点。请注意,单词边界也取决于语言环境。我认为使用标准java.text.BreakIterator是最好的方法。下面是java.sun.com教程中的一个示例
import java.text.BreakIterator;
import java.util.Locale;
public static void main(String[] args) {
String text = "\n" +
"\n" +
"For example I'm extracting a text String from a text file and I need those words to form an array. However, when I do all that some words end with comma (,) or a full stop (.) or even have brackets attached to them (which is all perfectly normal).\n" +
"\n" +
"What I want to do is to get rid of those characters. I've been trying to do that using those predefined String methods in Java but I just can't get around it.\n" +
"\n" +
"Every help appreciated. Thanx";
BreakIterator wordIterator = BreakIterator.getWordInstance(Locale.getDefault());
extractWords(text, wordIterator);
}
static void extractWords(String target, BreakIterator wordIterator) {
wordIterator.setText(target);
int start = wordIterator.first();
int end = wordIterator.next();
while (end != BreakIterator.DONE) {
String word = target.substring(start, end);
if (Character.isLetterOrDigit(word.charAt(0))) {
System.out.println(word);
}
start = end;
end = wordIterator.next();
}
}
来源:您可以使用
replaceAll()
方法:
String.replaceAll(",", "");
String.replaceAll("\\.", "");
String.replaceAll("\\(", "");
etc..要删除最后一个字符,请按所述操作 另外,删除不需要的字符的另一种方法是使用
.replace(oldCharacter,newCharacter)
方法
例如:
s = s.replace(",","");
及
最好的方法是Mark Byers解释的:
s = s.substring(0, s.length() - 1)
例如,如果我们想用ReplaceAll替换\to space“”,它就不能正常工作
String.replaceAll("\\", "");
或
谢谢:)我知道这不是什么难事,就是绕不过去。宪章里的字太多了。我该怎么打这个?谢谢。我设法为(int I=0;I
String.substring()
的源代码,我不认为这是一个错误的答案,但有一点是不可否认的。在“”replaceAll上试用它将替换所有字符,而不仅仅是最后一个字符。
s = s.replace(".","");
s = s.substring(0, s.length() - 1)
String.replaceAll("\\", "");
String.replaceAll("\\$", ""); //if it is a path