将字符串拆分为字符串数组 Java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14392057/
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
Splitting String into Array of Strings Java
提问by Andrey Chasovski
I have a String that looks like this
我有一个看起来像这样的字符串
The#red#studio#502#4
I need to split it into 3 different Strings in the array to be
我需要在数组中将它分成 3 个不同的字符串
s[0] = "The red studio"
s[1] = "502"
s[2] = "4"
The problem is the first one should have only words and the second and third should have only numbers...
问题是第一个应该只有单词,第二个和第三个应该只有数字......
I was trying to play with the s.split()
Method, but no luck.
我试图玩这个s.split()
方法,但没有运气。
回答by Srinivas
回答by Daniel Kaplan
I've decided to edit out my impl because I think that @Srinivas's is more elegant. I'm leaving the rest of my answer though because the tests are still useful. It passes on @Srinivas's example too.
我决定编辑我的 impl,因为我认为@Srinivas 的更优雅。不过,我将留下我的其余答案,因为这些测试仍然有用。它也传递了@Srinivas 的例子。
package com.sandbox;
import com.google.common.base.Joiner;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class SandboxTest {
@Test
public void testQuestionInput() {
String[] s = makeResult("The#red#studio#502#4");
assertEquals(s[0], "The red studio");
assertEquals(s[1], "502");
assertEquals(s[2], "4");
}
@Test
public void testAdditionalRequirement() {
String[] s = makeResult("The#red#studio#has#more#words#502#4");
assertEquals(s[0], "The red studio has more words");
assertEquals(s[1], "502");
assertEquals(s[2], "4");
}
private String[] makeResult(String input) {
// impl inside
}
}
回答by Kanagaraj M
Simply try: 'String s[]= yourString.split("#")' it will return string array....
只需尝试: 'String s[]= yourString.split("#")' 它会返回字符串数组....