在JavaScript中,我们可以在每个第3个字符处分割字符串
"foobarspam".match(/.{1,3}/g)
我试图找出如何在Java中执行此操作。有什么指针吗?
答案 0 :(得分:113)
你可以这样做:
String s = "1234567890";
System.out.println(java.util.Arrays.toString(s.split("(?<=\\G...)")));
产生:
[123, 456, 789, 0]
正则表达式(?<=\G...)
匹配一个空字符串,该字符串包含最后一个匹配(\G
),后跟三个字符(...
)之前((?<= )
)
答案 1 :(得分:80)
Java不提供功能齐全的分割实用程序,因此Guava libraries执行:
Iterable<String> pieces = Splitter.fixedLength(3).split(string);
查看Javadoc for Splitter;它非常强大。
答案 2 :(得分:44)
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
for (String part : getParts("foobarspam", 3)) {
System.out.println(part);
}
}
private static List<String> getParts(String string, int partitionSize) {
List<String> parts = new ArrayList<String>();
int len = string.length();
for (int i=0; i<len; i+=partitionSize)
{
parts.add(string.substring(i, Math.min(len, i + partitionSize)));
}
return parts;
}
}
答案 3 :(得分:4)
作为Bart Kiers答案的补充,我想补充一点,可以代替在正则表达式中使用三个点Center
代表三个字符,你可以写$(document).ready(function () {
if (window.location.pathname = '/all') {
$('body').css('overflow-y', 'auto');
} else {
$('body').css('overflow-y', 'hidden');
}
});
具有相同的含义。
然后代码如下所示:
...
使用它可以更容易地修改字符串长度,并且现在使用可变输入字符串长度来创建函数是合理的。这可以完成如下:
.{3}
IdeOne中的一个示例:http://ideone.com/rNlTj5
答案 4 :(得分:3)
最新条目。
以下是使用Java8流(一个衬里)的简洁实现:
String foobarspam = "foobarspam";
AtomicInteger splitCounter = new AtomicInteger(0);
Collection<String> splittedStrings = foobarspam
.chars()
.mapToObj(_char -> String.valueOf((char)_char))
.collect(Collectors.groupingBy(stringChar -> splitCounter.getAndIncrement() / 3
,Collectors.joining()))
.values();
输出:
[foo, bar, spa, m]
答案 5 :(得分:1)
这是一个迟到的答案,但无论如何我都会把它放在那里让任何新的程序员看到:
如果您不想使用正则表达式,和不希望依赖第三方库,则可以使用此方法, 在 2.80 GHz CPU (小于一毫秒)内 89920 和 100113 纳秒。它不像西蒙尼克森那样漂亮,但它有效:
/**
* Divides the given string into substrings each consisting of the provided
* length(s).
*
* @param string
* the string to split.
* @param defaultLength
* the default length used for any extra substrings. If set to
* <code>0</code>, the last substring will start at the sum of
* <code>lengths</code> and end at the end of <code>string</code>.
* @param lengths
* the lengths of each substring in order. If any substring is not
* provided a length, it will use <code>defaultLength</code>.
* @return the array of strings computed by splitting this string into the given
* substring lengths.
*/
public static String[] divideString(String string, int defaultLength, int... lengths) {
java.util.ArrayList<String> parts = new java.util.ArrayList<String>();
if (lengths.length == 0) {
parts.add(string.substring(0, defaultLength));
string = string.substring(defaultLength);
while (string.length() > 0) {
if (string.length() < defaultLength) {
parts.add(string);
break;
}
parts.add(string.substring(0, defaultLength));
string = string.substring(defaultLength);
}
} else {
for (int i = 0, temp; i < lengths.length; i++) {
temp = lengths[i];
if (string.length() < temp) {
parts.add(string);
break;
}
parts.add(string.substring(0, temp));
string = string.substring(temp);
}
while (string.length() > 0) {
if (string.length() < defaultLength || defaultLength <= 0) {
parts.add(string);
break;
}
parts.add(string.substring(0, defaultLength));
string = string.substring(defaultLength);
}
}
return parts.toArray(new String[parts.size()]);
}
答案 6 :(得分:1)
使用纯Java:
String s = "1234567890";
List<String> list = new Scanner(s).findAll("...").map(MatchResult::group).collect(Collectors.toList());
System.out.printf("%s%n", list);
产生输出:
[123,456,789]
请注意,这将丢弃剩余字符(在这种情况下为0)。
答案 7 :(得分:0)
您还可以在第n个字符处分割一个字符串,并将每个字符串放在List的每个索引中:
在这里,我列出了一个名为Sequence的字符串列表:
列出<字符串>序列
然后,我基本上将字符串“ KILOSO”每2个字分割一次。因此,“ KI”,“ LO”,“ SO”将合并到称为“序列”的列表的单独索引中。
字符串S = KILOSO
顺序= Arrays.asList(S.split(“(?<= \ G ..)”)));
所以当我在做:
System.out.print(Sequence)
它应该打印:
[KI,LO,SO]
验证我可以写:
System.out.print(Sequence.get(1))
它将打印:
LO
答案 8 :(得分:0)
我最近遇到了这个问题,这是我想出的解决方案
final int LENGTH = 10;
String test = "Here is a very long description, it is going to be past 10";
Map<Integer,StringBuilder> stringBuilderMap = new HashMap<>();
for ( int i = 0; i < test.length(); i++ ) {
int position = i / LENGTH; // i<10 then 0, 10<=i<19 then 1, 20<=i<30 then 2, etc.
StringBuilder currentSb = stringBuilderMap.computeIfAbsent( position, pos -> new StringBuilder() ); // find sb, or create one if not present
currentSb.append( test.charAt( i ) ); // add the current char to our sb
}
List<String> comments = stringBuilderMap.entrySet().stream()
.sorted( Comparator.comparing( Map.Entry::getKey ) )
.map( entrySet -> entrySet.getValue().toString() )
.collect( Collectors.toList() );
//done
// here you can see the data
comments.forEach( cmt -> System.out.println( String.format( "'%s' ... length= %d", cmt, cmt.length() ) ) );
// PRINTS:
// 'Here is a ' ... length= 10
// 'very long ' ... length= 10
// 'descriptio' ... length= 10
// 'n, it is g' ... length= 10
// 'oing to be' ... length= 10
// ' past 10' ... length= 8
// make sure they are equal
String joinedString = String.join( "", comments );
System.out.println( "\nOriginal strings are equal " + joinedString.equals( test ) );
// PRINTS: Original strings are equal true