英文:
Replace the first and last symbol in a string
问题
你可以使用Java中的indexOf
和lastIndexOf
方法来找到第一个[
和最后一个]
的位置,然后使用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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论