Java 如何在维护案例的同时替换字符串?
我想通过删除最后的s来替换字符串 范例Java 如何在维护案例的同时替换字符串?,java,Java,我想通过删除最后的s来替换字符串 范例 Sticks -> Stick STiCKs -> STiCK StICks -> StICK sticks -> stick 在使用 string.replace("sticks", "stick"); 不维护大小写,因为它区分大小写,所以我正在寻找更好的选择。一个可能的解决方案是正则表达式: StringBuffer sb = new StringBuffer(); Matcher matcher = Pattern.com
Sticks -> Stick
STiCKs -> STiCK
StICks -> StICK
sticks -> stick
在使用
string.replace("sticks", "stick");
不维护大小写,因为它区分大小写,所以我正在寻找更好的选择。一个可能的解决方案是正则表达式:
StringBuffer sb = new StringBuffer();
Matcher matcher = Pattern.compile("(stick)s", Pattern.CASE_INSENSITIVE) .matcher(inputString);
while(matcher.find()) {
matcher.appendReplacement(sb, matcher.group(1));
}
matcher.appendTail(sb);
String outputString = sb.toString();
编辑:这或多或少是String::replaceAll的作用,但是replaceAll没有提供不区分大小写的选项。如果您只需要删除
字符串末尾的
,您可以简单地使用substring
方法,如下所示:
String myString = "sTiCks";
myString = myString.substring(0, myString.length()-1);
// Result "sTiCk"
如果您不知道此部分将在哪里,需要从字符串中删除字符
或字符串
,可以尝试以下操作:
String myString = "sTiCks";
// Part you want to delete
String stringToDelete = "Ck";
// Find where that part starts inside your String
int index = myString.indexOf(stringToDelete);
// If found, use substring method to take only what is before and after that part
if (index >= 0)
myString = myString.substring(0, index) + myString.substring(index + stringToDelete.length(), myString.length());
// Result "sTis"
这将仅在第一次找到所需零件时删除该零件。但是,如果要删除的部分在字符串中出现多次,则可以将代码修改为:
String myString = "sTiCks";
// Part you want to delete
String stringToDelete = "s";
int index;
while ((index = myString.indexOf(stringToDelete)) >= 0)
myString = myString.substring(0, index) + myString.substring(index + stringToDelete.length(), myString.length());
// Result "TiCk"
我希望其中一个解决方案适合您的情况。您可以使用一个非常简单的正则表达式来完成此任务
(?i)
保证您的正则表达式不区分大小写
我真的不明白为什么到目前为止所有的答案都这么复杂。您只需检查最后一个字符,如果它是s
(或s
),则使用String#substring
()并省略最后一个字符:
String text = "STiCks";
char lastCharacter = text.charAt(text.length() - 1);
if (lastCharacter == 'S' || lastCharacter == 's') {
text = text.substring(0, text.length() - 1);
}
如果要将该方法应用于多个单词,例如在一个句子中,请首先标记该句子。然后将该方法应用于每个单词并重建句子
String sentence = StiCks are nice, I like sticks"
String[] words = sentence.split(" ");
StringJoiner joiner = new StringJoiner(" ");
for (String word : words) {
joiner.add(removePluralSuffix(word));
}
String result = joiner.toString();
或与流相同:
String result = Arrays.stream(sentence.split(" "))
.map(this::removePluralSuffix)
.collect(Collectors.joining(" "));
展示你的尝试。好的,给你一个主意,先找出lastIndexOf('s'),然后找出最后一个“s”的子字符串,然后使用str.replace(“s”),你到目前为止试过什么?但是字符串上的“棍子”可以是任何地方例如“他发现了一些棍子”“一些棍子在地上”“在那棵树上发现了棍子”更多您尝试过的内容请分享您的代码。尝试过的字符串。替换(“棍棒”,“棍棒”);我认为StringUtils.Replace(“Sticks”、“Sticks”);同样如此
String result = Arrays.stream(sentence.split(" "))
.map(this::removePluralSuffix)
.collect(Collectors.joining(" "));