【问题标题】:How to split a string array based on dynamic entries of values? [closed]如何根据值的动态条目拆分字符串数组? [关闭]
【发布时间】:2013-12-14 19:31:34
【问题描述】:

我正在尝试拆分现在存储在 String[] args 中的字符串数组(从控制台获得的输入)

host 9 7 1 router 5 8 11 lan 1 5 2 9

现在 args 接收值并将它们存储为

args[0] = "host", args[1] = "9", args[2] = "7" 以此类推。

字符串“host”、“router”和“lan”之后的值是动态生成的,即值的数量可以改变

例如,另一个实例可以是

host 0 4 3 9 router 4 9 2 lan 1 3 4 7

对于上面提到的例子我想创建一个

String[] hosts 将存储 0,4,3,9
String[] routers 将存储 4,9,2
String[] lans 将存储 1,3,4,7

我该怎么做?

【问题讨论】:

  • 带循环。或者,如果您想对其进行过度设计,请使用正则表达式。

标签: java arrays string split


【解决方案1】:
public static void main(String[] args) {

    String in = "host 0 4 3 9 router 4 9 2 lan 1 3 4 7";

    List<String> storage = Arrays.asList(in.split(" "));

    boolean isHost = false;
    boolean isRouter = false;
    boolean isLan = false;

    List<String> hostList = new ArrayList<String>();
    List<String> routerList = new ArrayList<String>();
    List<String> lanList = new ArrayList<String>();

    for(String val : storage){
        if("host".equals(val)){
            isHost = true;
            continue;
        }
        else if("router".equals(val)){
            isRouter = true;
            isHost = false; 
            continue;
        }
        else if("lan".equals(val)){
            isHost = false;
            isRouter = false;
            isLan = true;
            continue;
            }

        if(isHost){             
            hostList.add(val);
        }
        else if(isRouter){              
            routerList.add(val);
        }
        else if(isLan){             
            lanList.add(val);
        }
    }

    System.out.print("Host: "); System.out.println(hostList);
    System.out.print("Router: "); System.out.println(routerList);
    System.out.print("Lan: "); System.out.println(lanList);

}

输出:

Host: [9, 7, 1]
Router: [5, 8, 11]
Lan: [1, 5, 2, 9]

【讨论】:

  • 谢谢,正是我想要的!
猜你喜欢
  • 2021-03-02
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 2021-11-07
  • 1970-01-01
  • 1970-01-01
  • 2016-11-18
相关资源
最近更新 更多