Java:如何用一些字符拆分字符串? [英] Java: How to split a string by a number of characters?

查看:458
本文介绍了Java:如何用一些字符拆分字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在线搜索来解决这个问题,但我没有找到任何东西。

I tried to search online to solve this question but I didn't found anything.

我写了以下抽象代码来解释我问: / p>

I wrote the following abstract code to explain what I'm asking:

String text = "how are you?";

String[] textArray= text.splitByNumber(4); //this method is what I'm asking
textArray[0]; //it contains "how "
textArray[1]; //it contains "are "
textArray[2]; //it contains "you?"

方法splitByNumber每4个字符分割一个字符串text。如何创建此方法

The method splitByNumber splits the string "text" every 4 characters. How I can create this method??

很感谢

推荐答案

我想他想要的是一个字符串拆分为大小为4的子字符串。然后我将这样做一个循环:

I think that what he wants is to have a string split into substrings of size 4. Then I would do this in a loop:

List<String> strings = new ArrayList<String>();
int index = 0;
while (index < text.length()) {
    strings.add(text.substring(index, Math.min(index + 4,text.length())));
    index += 4;
}

这篇关于Java:如何用一些字符拆分字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆