Java字符串替换优先

Java字符串替换优先,java,string,replace,split,Java,String,Replace,Split,我正在读一串串的书 Is Mississippi a State where there are many systems. 我想用“t”或“t”替换每个单词中的第一个“s”或“s”(即保持大小写相同)…以便输出为: It Mitsissippi a Ttate where there are many tystems. 我试过了 s=s.replaceFirst(“(?i)s”,“t”);[这当然不起作用] 并尝试使用 string[].split(Pattern.quote(\\s))然

我正在读一串串的书

Is Mississippi a State where there are many systems.
我想用“t”或“t”替换每个单词中的第一个“s”或“s”(即保持大小写相同)…以便输出为:

It Mitsissippi a Ttate where there are many tystems.
我试过了

s=s.replaceFirst(“(?i)s”,“t”);[这当然不起作用]

并尝试使用 string[]
.split(Pattern.quote(\\s))
然后尝试找出如何
replaceFirst()
数组的每个元素
,然后将值返回到
字符串
[但无法找到正确的方法


我想
\\G
可能有助于在下一个单词时重新启动,但没有得到任何帮助。感谢使用这三种方法的任何帮助。

方法1:无需使用
替换
拆分
方法即可获得更好的性能

String str = "Is Mississippi a State where there are many systems.";
System.out.println(str);

char[] cArray = str.toCharArray();
boolean isFirstS = true;
for (int i = 0; i < cArray.length; i++) {
    if ((cArray[i] == 's' || cArray[i] == 'S') && isFirstS) {
        cArray[i] = (cArray[i] == 's' ? 't' : 'T');
        isFirstS = false;
    } else if (Character.isWhitespace(cArray[i])) {
        isFirstS = true;
    }
}
str = new String(cArray);

System.out.println(str);

注意:我更喜欢方法1,因为方法
replacefirt
split
、String
append
concat
我的方法对您提到的那些字符串方法的依赖性较小

String phrase;
String [] parts = phrase.split(" ");

for (int i = 0; i < parts.length; i++ ) {
    for (int j = 0; j < parts[i].length(); j++) {
        if (parts[i].charAt(j) == 's') {
            parts[i] = "t" + parts[i].substring(1);
            break;
        } else if (parts[i].charAt(0) == 'S') {
            parts[i] = "T" + parts[i].substring(1);
            break;
        }
    }
}

String modifiedPhrase = "";

for (int i = 0; i < parts.length; i++ ) {
    modifiedPhrase += parts[i] + " ";
}
字符串短语;
String[]parts=phrase.split(“”);
对于(int i=0;i
一个选项是将字符串拆分为单词,然后在每个单词上使用
string.replaceFirst()
将第一次出现的
s
替换为
t
(或任何其他您想要的字母):

更新:

It Mitsissippi a Ttate where there are many tystems.
我重构了我的解决方案,以找到任何
s
(大写或小写)的首次出现,并对其应用适当的转换

String input = "Is Mississippi a State where there are many systems.";
String[] parts = input.split(" ");
StringBuilder sb = new StringBuilder("");

for (int i=0; i < parts.length; ++i) {
    if (i > 0) {
        sb.append(" ");
    }
    int index = parts[i].toLowerCase().indexOf('s');
    if (index >= 0 && parts[i].charAt(index) == 's') {
        sb.append(parts[i].replaceFirst("s", "t"));
    }
    else {
        sb.append(parts[i].replaceFirst("S", "T"));
    }
}

System.out.println(sb.toString());

使用下面对Tim Biegeleisen答案的修正(在编辑他的帖子之前)

编辑-您可以使用concat()

更新

    String input = "Is Mississippi a State where there are many Systems.";
    String[] parts = input.split(" ");
    //StringBuilder sb = new StringBuilder("");

    String output = "";

    for (String part : parts) {
        output = output.concat(part.replaceFirst("s", "t") + " ");
    }

    String[] parts2 = output.split(" ");

    output = "";

    for (String part : parts2) {
        output = output.concat(part.replaceFirst("S", "T") + " ");
    }
    System.out.println(output);

我创建了一个-

  • 是通用的,
  • 不使用
    替换
    拆分
    ,以及
  • 只使用一个循环
以下是我的代码片段:

public static String replaceFirstOccurance(String sentence, char toChange, char changeWith) {
    StringBuilder temp = new StringBuilder();

    boolean changed = false;
    for (int i = 0; i < sentence.length(); i++) {
        if (!changed) {
            if (sentence.charAt(i) == toChange) {
                temp.append(changeWith);
                changed = true;
            } else if (sentence.charAt(i) == Character.toUpperCase(toChange)) {
                temp.append(Character.toUpperCase(changeWith));
                changed = true;
            } else {
                temp.append(sentence.charAt(i));
            }
        } else {
            if (sentence.charAt(i) == ' ') {
                changed = false;
            }
            temp.append(sentence.charAt(i));
        }
    }

    return temp.toString();
}
publicstaticstringreplaceFirstOccurance(字符串语句、chartoChange、charchangeWith){
StringBuilder temp=新的StringBuilder();
布尔值=假;
for(int i=0;i<句子长度();i++){
如果(!已更改){
if(句子字符(i)=toChange){
临时附加(changeWith);
更改=正确;
}else if(句子.charAt(i)=字符.toUpperCase(toChange)){
临时追加(Character.toUpperCase(changeWith));
更改=正确;
}否则{
临时附加(句子字符(i));
}
}否则{
如果(句子字符(i)=''){
更改=错误;
}
临时附加(句子字符(i));
}
}
返回温度toString();
}

还有一个很好的、紧凑的、基于流的解决方案:

String result = Stream.of(s.split(" "))
    .map(t -> t.replaceFirst("s", "t"))
    .map(t -> t.replaceFirst("S", "T"))
    .collect(Collectors.joining(" "));


如果您只需要替换每件作品中的第一个或多个,为什么要将“是”替换为“它”?你能纠正一下布局并给出一个或多个清晰的例子吗?知道了每个“s”或“s”的第一次出现@Hedgebox我希望你已经得到了答案。但是我们提供了一种不同的方法来解决您的问题。请看我的答案。JavaScript中的一行代码:
。替换(/(\S*?)([sS])(\S*)/g,($1,$2,$3)=>$1+($2=='S'?'t':'t')+$3)
@im biegeleisen您的解决方案经过一些调整后非常完美。检查我的帖子这对于像“Systems”这样的单词来说,结果是错误的,带有大写字母“S”和小写字母“S”(至少我理解这个问题)。
Systems
->
Tyttems
。。。有什么问题吗?@Tim Biegeleisen:msandiford似乎是对的。。。我刚试过…我想让“系统”变成“系统”。。。只有第一次出现“S”或“S”到“T”或“T”@BDCoder抱歉,我有几个打字错误。我已经修复了它们,并验证了实际输出是否符合预期。我确实想使用字符串方法……有没有不使用StringBuilder的方法?@Hedgebox FYI
StringBuilder
提供了比下面评论中的
+
@Thush Fdo:msandiford更好的性能……似乎是正确的。。。我刚试过…我想让“系统”变成“系统”。。。只有“S”或“S”到“T”或“T”的第一次出现。当我将“系统”改为“系统”时,代码生成的是“Tyttems”而不是“Tystems”。@Hedgebox:另一种解决方案,在我更新答案时使用两个循环。但这会影响你的表现。请随意使用任何建议。@Thush Fdo不要另眼相看,你的答案中太多的编辑让一些人难以理解。@cricket_007使用不同的方法编辑:)ASCII移位。。。它会起作用的,但它对这一个非常具体problem@cricket_007对但我希望这将提供比其他答案更快的解决方案。@mmuzahid:tks您的解决方案,但我正在尝试更好地了解replaceFirst的用法…此时不使用StringBuilder。@Hedgebox,请参见编辑部分,使用
replaceFirst
    String input = "Is Mississippi a State where there are many Systems.";
    String[] parts = input.split(" ");
    //StringBuilder sb = new StringBuilder("");

    String output = "";

    for (String part : parts) {
        output = output.concat(part.replaceFirst("s", "t") + " ");
    }

    String[] parts2 = output.split(" ");

    output = "";

    for (String part : parts2) {
        output = output.concat(part.replaceFirst("S", "T") + " ");
    }
    System.out.println(output);
public static String replaceFirstOccurance(String sentence, char toChange, char changeWith) {
    StringBuilder temp = new StringBuilder();

    boolean changed = false;
    for (int i = 0; i < sentence.length(); i++) {
        if (!changed) {
            if (sentence.charAt(i) == toChange) {
                temp.append(changeWith);
                changed = true;
            } else if (sentence.charAt(i) == Character.toUpperCase(toChange)) {
                temp.append(Character.toUpperCase(changeWith));
                changed = true;
            } else {
                temp.append(sentence.charAt(i));
            }
        } else {
            if (sentence.charAt(i) == ' ') {
                changed = false;
            }
            temp.append(sentence.charAt(i));
        }
    }

    return temp.toString();
}
String result = Stream.of(s.split(" "))
    .map(t -> t.replaceFirst("s", "t"))
    .map(t -> t.replaceFirst("S", "T"))
    .collect(Collectors.joining(" "));
String ss = "Is Mississippi a State where there are many systems.";

String out = "";//replaced string
for (String s : ss.split(" ")) {
    int index = s.toUpperCase().indexOf('S');
    out += (s.replaceFirst("[s,S]", index!= -1 && s.charAt(index) == 'S' 
               ? "T" : "t")) + " ";
}

System.out.println(out);