繁体   English   中英

如何在特定索引处将String分成两部分,并将这两部分都保留在Java中?

[英]How can I split a String into two at a certain Index and keep both parts in Java?

我可以用substring()将其拆分两次,然后分别保存两个半部,但是由于我要提高效率,因此我需要一个更好的解决方案,理想地将两个半部一次保存在String []中。

正如@Jon Skeet已经提到的那样 ,您应该真正地分析性能,因为我无法想象,这实际上是瓶颈。 但是,另一个解决方案是拆分String的char数组:

String str = "Hello, World!";

int index = 4;
char[] chs = str.toCharArray();
String part1 = new String(chs, 0, index);
String part2 = new String(chs, index, chs.length - index);

System.out.println(str);
System.out.println(part1);
System.out.println(part2);

打印:

Hello, World!
Hell
o, World!

这可能是一个通用的实现:

public static String[] split(String str, int index) {
    if (index < 0 || index >= str.length()) {
        throw new IndexOutOfBoundsException("Invalid index: " + index);
    }
    char[] chs = str.toCharArray();
    return new String[] { new String(chs, 0, index), new String(chs, index, chs.length - index) };
}

这种方法的问题是,它比简单的substring()调用效率 (!),因为与使用两个substring()调用(数组是另外创建的对象)相比,我的代码创建的对象更多。 实际上, substring()完全可以执行我在代码中所做的事情,而无需创建数组。 唯一的区别是,两次调用substring()对索引进行两次检查。 与对象分配成本进行比较取决于您。

尝试使用stringName.split('*') ,其中*是您要分割字符串的字符。 它返回一个String数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM