例如,我有这个字符串参数: Blabla,1,Yoooooooo,Stackoverflow,foo,chinese
我想获取字符串 testCaseParams
直到第三个逗号:Blabla,1,Yooooooo
然后从原始字符串中删除它和逗号,这样我就得到了这个Stackoverflow,foo,chinese
我正在尝试此代码,但 testCaseParams
仅显示前两个值(获取第二个逗号的索引,而不是第三个...)
//Get how many parameters this test case has and group the parameters
int amountOfInputs = 3;
int index = params.indexOf(',', params.indexOf(',') + amountOfInputs);
String testCaseParams = params.substring(0,index);
params = params.replace(testCaseParams + ",","");
最佳答案
您可以将当前找到的逗号的索引保存在变量中并进行迭代,直到找到第三个逗号:
int index = 0;
for (int i=0; i<3; i++) index = str.indexOf(',', index);
String left = str.substring(0, index);
String right = str.substring(index+1); // skip comma
编辑:要验证字符串,只需检查 index == -1
即可。如果是,则字符串中没有 3 个逗号。
关于java - 获取第三个逗号的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48225765/