我需要將字串截斷為 n 個字符,忽略空格。
假設我的字串是:
String a = "Hello World!"
如果 n=7,那么輸出應該是:
Hello Wo
我可以通過分割空白然后將其組合回來來做到這一點。但是使用 Java 8 有更好的解決方案嗎?
我試過的其他解決方案:
String a = "Hello World!!";
Pattern pattern = Pattern.compile("[^\\s]{5}");
Matcher matcher = pattern.matcher(a);
if (matcher.find())
{
System.out.println(matcher.group(1));
}
但它沒有用。謝謝!!
uj5u.com熱心網友回復:
String a = "Hello World!";
int n = 7;
n = n a.substring(0, n).split(" ").length - 1;
a = a.substring(0, n);
System.out.println(a);
uj5u.com熱心網友回復:
另一種對邊緣情況更靈活的實用解決方案->如果最后一個索引也是空格怎么辦,例如
String ori = "Hello World";
int cCount = 6;
String endSub = ori.substring(cCount);
Stream<Character> endSubStream = endSub.chars().mapToObj(c -> (char) c);
int whitespacesEnd = (int)endSubStream.filter(p -> Character.isWhitespace(p.charValue())).count();
String beginSub = ori.substring(0, cCount);
Stream<Character> beginSubStream = beginSub.chars().mapToObj(c -> (char) c);
int whitespaces = (int)beginSubStream.filter(p -> Character.isWhitespace(p.charValue())).count();
String text = ori.substring(0, cCount whitespaces whitespacesEnd);
System.out.println(text);
https://www.online-java.com/D4qarKf5Cl
uj5u.com熱心網友回復:
我能想到的一種解決方案:
// Pseudo-code
string // i.e: "Hello World"
n // i.e = 7
counter1, counter2
for character in string {
if counter1 == n {
break;
}
if character is not `space` {
counter1;
} else {
counter2;
}
}
return string.subString(0, counter1 counter2);
uj5u.com熱心網友回復:
這應該可以解決您的要求。
String stringToBeProcessed = "Hello World! to you";
int count = 0;
int limit = 7;
StringBuilder sb = new StringBuilder();
for(Character c : stringToBeProcessed.toCharArray()){
if(!Character.isSpaceChar(c)){
count = count 1;
}
if(count > limit){
break;
} else {
sb.append(c);
}
}
System.out.println(sb);
uj5u.com熱心網友回復:
String test(int cnt, String string) {
AtomicInteger n = new AtomicInteger(cnt);
return string
.chars()
.boxed()
.peek(value -> {
if (!Character.isWhitespace(value)) {
n.decrementAndGet();
}
})
.takeWhile(value -> n.get() >= 0)
.map(Character::toString)
.collect(Collectors.joining());
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/418879.html
標籤:
上一篇:用字串填充Double串列
下一篇:從R中的復雜字串創建多行
