简体   繁体   English

将字符串拆分为字符串数组Java

[英]Splitting String into Array of Strings Java

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()方法,但没有运气。

String s= "The#red#studio#502#4";
String[] array = s.split("#(?=[0-9])");
for(String str : array)
{
  System.out.println(str.replace('#',' '));
}

Output: 输出:

The red studio  
502  
4  

Ideone link . Ideone 链接

I've decided to edit out my impl because I think that @Srinivas's is more elegant. 我决定编辑我的impl因为我认为@ Srinivas更优雅。 I'm leaving the rest of my answer though because the tests are still useful. 我将离开我的其余部分,因为测试仍然有用。 It passes on @Srinivas's example too. 它也传递了@ 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
    }
}

只需尝试:'String s [] = yourString.split(“#”)'它将返回字符串数组....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM