I need to truncate a String upto n characters ignoring whiteSpace.
Suppose My String is:
String a = "Hello World!"
And if n=7, then the output should be:
Hello Wo
I can do that by splitting on whitespace and then combining it back. but any better solution using Java 8?
other Solution I tried:
String a = "Hello World!!";
Pattern pattern = Pattern.compile("[^\\s]{5}");
Matcher matcher = pattern.matcher(a);
if (matcher.find())
{
System.out.println(matcher.group(1));
}
But it didn't work. Thanks!!
CodePudding user response:
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);
CodePudding user response:
One solution I can think of:
// 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);
CodePudding user response:
One other pragmatic solution which is more flexible for edge cases -> what if the last index is also a whitespace e.g.
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);
