gpt4 book ai didi

java - 如何在第 n 次出现分隔符之前进行子字符串化?

转载 作者:搜寻专家 更新时间:2023-10-31 19:42:57 27 4
gpt4 key购买 nike

first;snd;3rd;4th;5th;6th;...

如何在第三次出现 ; 分隔符后拆分上面的内容?特别是不必 value.split(";") 将整个字符串作为数组,因为我不需要将值分开。只是字符串的第一部分,直到第 n 次出现。

期望的输出是:第一;第二;第三。我只需要将其作为字符串子字符串,而不是拆分分隔值。

最佳答案

使用StringUtils.ordinalIndexOf()来自 Apache

查找字符串中的第 n 个索引,处理 null。此方法使用 String.indexOf(String)。

参数:

str - the String to check, may be null

searchStr - the String to find, may be null

ordinal - the n-th searchStr to find

返回:搜索字符串的第n个索引,如果没有匹配或空字符串输入则为-1(INDEX_NOT_FOUND)

this way, no libraries required :

public static int ordinalIndexOf(String str, String substr, int n) {
int pos = str.indexOf(substr);
while (--n > 0 && pos != -1)
pos = str.indexOf(substr, pos + 1);
return pos;
}

关于java - 如何在第 n 次出现分隔符之前进行子字符串化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53764906/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com