string字符串用逗号隔开在java中,有两个方法可以用逗号把string分开
一个是
public string[] split(string regex) { return split(regex, 0); }
另一个是
public string[] split(string regex, int limit) { /* fastpath if the regex is a (1)one-char string and this character is not one of the regex's meta characters ".$|()[{^?*+\\", or (2)two-char string and the first char is the backslash and the second is not the ascii digit or ascii letter. */ char ch = 0; if (((regex.value.length == 1 && ".$|()[{^?*+\\".indexof(ch = regex.charat(0)) == -1) || (regex.length() == 2 && regex.charat(0) == '\\' && (((ch = regex.charat(1))-'0')|('9'-ch)) < 0 && ((ch-'a')|('z'-ch)) < 0 && ((ch-'a')|('z'-ch)) < 0)) && (ch < character.min_high_surrogate || ch > character.max_low_surrogate)) { int off = 0; int next = 0; boolean limited = limit > 0; arraylist<string> list = new arraylist<>(); while ((next = indexof(ch, off)) != -1) { if (!limited || list.size() < limit - 1) { list.add(substring(off, next)); off = next + 1; } else { // last one //assert (list.size() == limit - 1); list.add(substring(off, value.length)); off = value.length; break; } } // if no match was found, return this if (off == 0) return new string[]{this}; // add remaining segment if (!limited || list.size() < limit) list.add(substring(off, value.length)); // construct result int resultsize = list.size(); if (limit == 0) { while (resultsize > 0 && list.get(resultsize - 1).length() == 0) { resultsize--; } } string[] result = new string[resultsize]; return list.sublist(0, resultsize).toarray(result); } return pattern.compile(regex).split(this, limit); }
1.如果我们的需求是要让分隔符号可以兼容中英文逗号可以用
split(string regex)
比如下面的例子
2.如果我们的需求是取到第一个逗号前面的字符串适合用
split(string regex, int limit)
以逗号为分割符拼接字符串的技巧答:
不用那么多if判断,让人思维混乱,直接到最后使用deletecharat方法去除最后一个逗号即可。
实现代码如下所示stringbuffer sb = new stringbuffer();for (string str: list) {sb.append(str).append(",");}string keywordstr = sb.deletecharat(sb.length() - 1).tostring();
以上就是java怎么实现string字符串用逗号隔开的详细内容。