Java 如何在一定长度后使用拆分字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33696011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use split a string after a certain length?
提问by newborn
I want to split a string after a certain length.
我想在一定长度后拆分字符串。
Let's say we have a string of "message"
假设我们有一串“消息”
Who Framed Roger Rabbit
Split like this :
像这样拆分:
"Who Framed" " Roger Rab" "bit"
And I want to split when the "message" variable is more than 10.
当“消息”变量超过 10 时,我想拆分。
my current split code :
我当前的拆分代码:
private void sendMessage(String message){
// some other code ..
String dtype = "D";
int length = message.length();
String[] result = message.split("(?>10)");
for (int x=0; x < result.length; x++)
{
System.out.println(dtype + "-" + length + "-" + result[x]); // this will also display the strd string
}
// some other code ..
}
采纳答案by Andy Turner
I wouldn't use String.split
for this at all:
我根本不会用String.split
这个:
String message = "Who Framed Roger Rabbit";
for (int i = 0; i < message.length(); i += 10) {
System.out.println(message.substring(i, Math.min(i + 10, message.length()));
}
Addition 2018/5/8:
2018/5/8 补充:
If you are simply printing the parts of the string, there is a more efficient option, in that it avoids creating the substrings explicitly:
如果您只是打印字符串的各个部分,则有一个更有效的选项,因为它避免了显式创建子字符串:
PrintWriter w = new PrintWriter(System.out);
for (int i = 0; i < message.length(); i += 10) {
w.write(message, i, Math.min(i + 10, message.length());
w.write(System.lineSeparator());
}
w.flush();
回答by TheLostMind
This will work for you. Works for any length of message.
这对你有用。适用于任何长度的消息。
public static void main(String[] args) {
String message = "Who Framed Roger Rab bit";
if (message.length() > 10) {
Pattern p = Pattern.compile(".{10}|.{1,}$");
Matcher m = p.matcher(message);
while (m.find()) {
System.out.println(m.group());
}
}
}
O/ P :
开/关:
Who Framed
Roger Rab
bit
回答by James Harrison
You could use a regex find, rather than a split
something like this:
[\w ]{0,10}
您可以使用正则表达式查找,而不是像这样的拆分:
[\w ]{0,10}
Pattern p = Pattern.compile("[\w ]{0,10}");
Matcher m = p.matcher("who framed roger rabbit");
while (m.find()) {
System.out.println(m.group());
}
回答by PeterK
I think Andy's solution would be the best in this case, but if you wanted to use a regex and split you could do
我认为安迪的解决方案在这种情况下是最好的,但是如果您想使用正则表达式并拆分,您可以这样做
"Who Framed Roger Rabbit ".split("(?<=\G.{10})");