在 JavaScript 中,这是我们如何在每个第三个字符处分割一个字符串
"foobarspam".match(/.{1,3}/g)
我正在尝试在Java中解决这个问题。有什么建议吗?
你可以这样做:
String s = "1234567890";
System.out.println(java.util.Arrays.toString(s.split("(?<=\\G...)")));
它产生:
[123, 456, 789, 0]
正则表达式(?<=\G...)
匹配一个空字符串,该空字符串具有上一次匹配(\G
)后面三个字符(...
)之前的特征((?<= )
)。
[123, 4567890]
:( - Evren YurtesenJava没有提供非常全面的字符串分割工具,因此Guava库提供了这样的工具:
Iterable<String> pieces = Splitter.fixedLength(3).split(string);
看看Splitter的Javadoc吧,它非常强大。
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}
。String bitstream = "00101010001001010100101010100101010101001010100001010101010010101";
System.out.println(java.util.Arrays.toString(bitstream.split("(?<=\\G.{3})")));
通过这种方式,修改字符串长度会更容易,并且现在可以使用变量输入字符串长度来创建函数。 可以像下面这样完成:
public static String[] splitAfterNChars(String input, int splitLen){
return input.split(String.format("(?<=\\G.{%1$d})", splitLen));
}
IdeOne中的示例:http://ideone.com/rNlTj5
%1$d
将被替换为变量splitLen
的十进制值。
否则,regex101.com对您也可能非常有帮助。 - Frodo晚进。
下面是使用Java8 streams的简洁实现,一行代码:
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]
/**
* 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()]);
}
使用纯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)。
我会从类似这样的东西开始
public List<String> split(String str, int interval) {
if (str.length() <= interval) {
return List.of(str);
}
var subStrings = new ArrayList<String>();
int pointer = 0;
while (str.length() > pointer) {
String substring = str.substring(pointer, pointer + interval);
subStrings.add(substring);
pointer += interval;
}
return subStrings;
}
您还可以将字符串在每个第n个字符处拆分,并将它们放入列表的每个索引中:
这里我创建了一个名为Sequence的字符串列表:
List < String > Sequence
然后,我基本上是通过每2个字母来拆分字符串“KILOSO”。因此,“KI”、“LO”和“SO”将被合并到名为Sequence的列表的单独索引中。
String S = KILOSO
Sequence = Arrays.asList(S.split("(?<=\G..)"));
所以当我执行以下操作时:
它应该打印:System.out.print(Sequence)
[KI,LO,SO]
以验证我可以编写:
它将打印出:System.out.print(Sequence.get(1))
LO
我最近遇到了这个问题,这是我想出的解决方案
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