java - 如何在特定点拆分字符串?
问题描述
我发现很难按照我想要的方式拆分我的字符串,这个平台上的答案都不符合我的要求。
我有字符串:
String s = "1 13 3 1 111 0 18 3";
我想要的是拆分它并分别打印这两个部分。
我想在有空间的地方拆分它,并指定应该拆分的空间。
例如,在空间号 4 处拆分字符串,以打印第一部分:1 13 3 1
第二部分:111 0 18 3
解决方案
对我来说听起来像是算法问题。
这是我的解决方案。这不是最有效的算法,但我这样做是为了让你很容易理解。
String s = "1 13 3 1 111 0 18 3";
String[] spitedString = s.split(" "); //Split by white spaces
int halfIndex = spitedString.length / 2; //Find the center index to divide the string into first and second half.
String[] firstHalf = Arrays.copyOfRange(spitedString, 0, halfIndex); //First half of String.
String[] secondHalf = Arrays.copyOfRange(spitedString, halfIndex, spitedString.length - 1); //Second half of String.
//You could loop through the parts
for(String c: firstHalf){
System.out.println(c);
}
//Or put it into one String
StringBuilder sb = new StringBuilder();
for(String c: secondHalf){
sb.append(c); //append string
sb.append(" "); //and append white space
}
System.out.println(sb);
编辑OP 的请求“我可以针对第一个空间,或第五个或任何其他特定条件,假设我有 int target = someIntCalue;”。
当然,逻辑是相同的,只需替换halfIndex
为您的targetIndex
. 这个想法是halfIndex
划分字符串的索引。
如果您有任何问题,请告诉我。谢谢。
推荐阅读
- c++ - 从 'wchar_t' 转换为 'const _Elem',可能会丢失数据
- php - 从包外部访问包配置值
- macos - 在 github 上使用 Sectigo 证书进行代码签名
- c++ - 在图遍历中找到最小路径的有效方法
- tailwind-css - 如何做光标:group-hover Tailwind Css中的指针?
- laravel - 通过 Laravel 8.x 中的控制器动态更改应用名称
- oracle - ORA-01292: 使用在线目录时无法使用日志挖掘器访问日志文件
- jenkins-groovy - 作业 DSL 脚本参考
- pandas - pd DataFrame,需要加列,一次性将文本字符串date_time解析成pandas year、dayOfWeek等
- html - 在纯 CSS 中创建第二个边框