我正在尝试将字符串拆分为数组。这应该很好,因为str.split(" ")
应该可以正常工作,但是字符串实际上是"xyz 100b\nabc 200b\ndef 400b"
的形式。我想知道解决这个问题的最佳方法是什么。我还需要以它们给出的格式返回4个字符串。下面是我现在尝试的方法,但是没有正确地拆分数组。我的目标是将数组拆分为["xyz", "100b", "abc", "200b", "def", "400b"]
public static String solution(String words){
String array[] = words.split(" ");
/*
There's a lot of other code manipulating the array to get 4 figures in the
end. This doesn't matter, it's just splitting the array and the return that
is my issue
In the end I will have 4 integers that I want to return in a similar way
that they gave them to me.
*/
return "answer 1" + String.valueOf(num1) + "b\n" +
"answer2 " + String.valueOf(num2) + "b\n" +
"answer 3" + String.valueOf(num3) + "b\n" +
"answer4 " + String.valueOf(num4) + "b\n";
}
编辑:
String array [] = str.split("\n| ")
将根据需要拆分数组,谢谢A.Oubidar
答案 0 :(得分:2)
希望我能正确理解您的问题,但是如果您要提取数字并以特定格式返回它们,可以这样:
suspend fun getCharacterFilms(serverRequest: ServerRequest) = ok()
.bodyAndAwait(starWarsApiWebClient.findCharacter(serverRequest.pathVariable("id").toInt())
.flatMapMerge {
it.films.asFlow()
}.flatMapMerge {
starWarsApiWebClient.findFilm(it)
})
这是执行后答案的值:
// Assuming the String would be like a repetition of [word][space][number][b][\n]
String testString = "xyz 100b\nabc 200b\ndef 400b";
// Split by both endOfLine and space
String[] pieces = testString.split("\n| ");
String answer = "";
// pair index should contain the word, impair is the integer and 'b' letter
for (int i = 0; i < pieces.length; i++) {
if(i % 2 != 0 ) {
answer = answer + "answer " + ((i/2)+1) + ": " + pieces[i] + "\n";
}
}
System.out.println(answer);
答案 1 :(得分:1)
您应该将此代码放在“返回”中,而不是已经存在的代码中。
return "answer 1" + array[0] + "b\n" +
"answer 2 " + array[1] + "b\n" +
"answer 3" + array[2] + "b\n" +
"answer 4 " + array[3] + "b\n";
答案 2 :(得分:1)
split()
方法使用一个正则表达式作为参数。这:input.split("\\s+")
将在空白处分割(\ s =空格,+ = 1或更大)。
您的问题尚不清楚,但是如果您要提取'100','200'等,则正则表达式也非常有用。您可以将每行插入正则表达式以提取值。有很多教程(对于“ java regexp示例”,仅是Google)。