在Java中从字符串中心解析信息
假设我有以下文本字符串: “第一:中间:最后” 我只想从这个字符串中提取“中心”。然而,我不知道什么将在开始,结束,或字符串的中心。我所知道的是冒号会将三段线分开,我需要的部分是冒号之间的部分 使用Java,我能完成这项任务的最干净的方法是什么在Java中从字符串中心解析信息,java,string,performance,Java,String,Performance,假设我有以下文本字符串: “第一:中间:最后” 我只想从这个字符串中提取“中心”。然而,我不知道什么将在开始,结束,或字符串的中心。我所知道的是冒号会将三段线分开,我需要的部分是冒号之间的部分 使用Java,我能完成这项任务的最干净的方法是什么 提前非常感谢您抽出时间。从逻辑上讲,我会(出于这种效果)离开: 使用String.split()并获取数组中的第二项 由于您只需要中心,因此可以使用适当的索引执行子字符串。这将比split()方法更有效,因为您将创建更少的字符串和数组实例 public
提前非常感谢您抽出时间。从逻辑上讲,我会(出于这种效果)离开: 使用
String.split()
并获取数组中的第二项
由于您只需要中心,因此可以使用适当的索引执行子字符串。这将比split()方法更有效,因为您将创建更少的字符串和数组实例
public class Main {
public static void main(String[] args) {
String fullStr = "first:center:last";
int firstColonIndex = fullStr.indexOf(':');
int secondColonIndex = fullStr.indexOf(':', firstColonIndex + 1);
String centerStr = fullStr.substring(firstColonIndex + 1, secondColonIndex);
System.out.println("centerStr = " + centerStr);
}
}
一个我认为最快的基于非正则表达式的解决方案:
String string = "left:center:right";
String center = string.substring(string.indexOf(':') + 1, string.lastIndexOf(':'))
这是我在2行中所做的3行代码…见鬼…也可以在1行中完成…是的,但它避免使用split();)
public class Main {
public static void main(String[] args) {
String fullStr = "first:center:last";
int firstColonIndex = fullStr.indexOf(':');
int secondColonIndex = fullStr.indexOf(':', firstColonIndex + 1);
String centerStr = fullStr.substring(firstColonIndex + 1, secondColonIndex);
System.out.println("centerStr = " + centerStr);
}
}
String string = "left:center:right";
String center = string.substring(string.indexOf(':') + 1, string.lastIndexOf(':'))