替换字符串中的第一个和最后一个符号。

huangapple go评论72阅读模式
英文:

Replace the first and last symbol in a string

问题

你可以使用Java中的indexOflastIndexOf方法来找到第一个[和最后一个]的位置,然后使用substring方法将它们从输入字符串中删除。以下是一个示例代码:

String input = "[N-[3-(1,3-ChemComp-2-yl)-6]-(compound-2]";
int firstBracketIndex = input.indexOf("[");
int lastBracketIndex = input.lastIndexOf("]");

if (firstBracketIndex != -1 && lastBracketIndex != -1) {
    String output = input.substring(0, firstBracketIndex) + input.substring(firstBracketIndex + 1, lastBracketIndex) + input.substring(lastBracketIndex + 1);
    System.out.println(output);
} else {
    // 输入字符串中没有找到匹配的方括号
    System.out.println("无法找到匹配的方括号。");
}

这段代码将从输入字符串中删除第一个[和最后一个],并输出结果。

英文:

I have an input string

[N-[3-(1,3-ChemComp-2-yl)-6]-(compound-2]

I want the output as

N-[3-(1,3-ChemComp-2-yl)-6]-(compound-2 

That is I want to remove the first occurance of [ and the last occurance of ]. I Tried using str.replace() but it replaces all the instances of the character. While replaceFirst only replaces character and it doesn't allow me enter the symbol [.

How do I remove the first [ and the last ] of my input string in java?

答案1

得分: 1

You can use the substring method:

String s = "[N-[3-(1,3-ChemComp-2-yl)-6]-(compound-2)]";
String r = s.substring(1, s.length() - 1);
System.out.println(r);
英文:

Use can use substring method

String s = "[N-[3-(1,3-ChemComp-2-yl)-6]-(compound-2]";
String r = s.substring(1, s.length() - 1);
System.out.println(r);

huangapple
  • 本文由 发表于 2020年7月28日 15:53:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/63129425.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定