我试图将一个长字符串切成该字符串的行,行的长度由函数决定。该功能不会剪切中间的单词。
我尝试了很多方法来使用子字符串等来做到这一点,但我不太擅长字符串操作。我在网上发现了一个类似的问题,但它是在 JavaScript 中,并且一些代码我无法完全翻译为 Java(也许是因为我对此缺乏经验......)
public static List<String> descriptionFormatter(String string, int amt)
{
String[] splitted = string.split(" ");
String part = "";
List<String> finalDesc = new ArrayList<String>();
for(int i = 0 ; i < splitted.length; i++)
{
part = part + " " + splitted[i];
if(part.length() >= amt)
{
finalDesc.add(part);
part = "";
}
}
return finalDesc;
}
例如 我有一个字符串“ Hello World 苹果橙葡萄汁意大利面酱牛奶” 我想每 34 个字符剪切一次(考虑到上述所有要求) 所以我打电话
descriptionFormatter(string, 34);
想要的结果是字符串数组/列表:
Hello World 苹果橙葡萄汁
意大利面酱牛奶
实际结果:
- Hello World 苹果橙葡萄汁
我已经几乎让它工作了,但有时它会跳过末尾的剩余单词并在第一个单词之前添加空格。如何让它按照我的预期运行?
最佳答案
您可以尝试使用两个索引(例如 beginIndex
和 endIndex
)遍历输入 string
,并随时从输入 string
中获取substrings
:
public static List<String> descriptionFormatter(String str, int amt) {
List<String> result = new ArrayList<>();
// trim the input string to avoid empty strings at the end
str = str.trim();
int beginIndex = 0;
int endIndex = amt;
final int length = str.length();
while(endIndex < length) {
// if we landed on something other than space
// increase the end index for the substring
// until we hit a space
while(endIndex < length && str.charAt(endIndex) != ' ') {
++endIndex;
}
result.add(str.substring(beginIndex, endIndex).trim());
beginIndex = endIndex;
endIndex += amt;
}
// Add the last string if any left
if(beginIndex < length) {
result.add(str.substring(beginIndex).trim());
}
return result;
}
public static void main(String[] args) {
String str = "hello world apple orange grapes juice spagehtti sauce milk";
descriptionFormatter(str, 34).forEach(System.out::println);
}
输出:
hello world apple orange grapes juice
spagehtti sauce milk
关于java - 如何每隔n个字符截取一个字符串?但只有当有空格时才会剪切,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54485744/