如何将字符串拆分为不同的变量 [英] How to Split a String into Different Variables

查看:81
本文介绍了如何将字符串拆分为不同的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下代码:

String s = "{U1,U2,U3},{U5,U7},{U4,U6,U8}";

如何使它看起来像下面?

String s1 = {U1,U2,U3};
String s2 = {U5,U7};
String s3 = {U4,U6,U8};

s中的组合可以是任何形式. s1,s2,s3是不同的字符串.

解决方案

这是我的代码:

public class SplitString {
    public static void main(String[] args) {

        String s ="{U1,U2,U3},{U5,U7},{U4,U6,U8}";
        String[] splitted = s.split("},");

        // add the end brace for every entry except the last
        for (int i=0 ; i < splitted.length-1 ; i++) {
            splitted[i]=splitted[i] + "}";
        }

        // print out the string array
        for (int i=0; i< splitted.length ; i++) {
            System.out.println("String s"+i+" = "+splitted[i]);
        }
    }
}

每次遇到两个字符},时都会拆分,将其放入拆分"字符串数组中,然后遍历String数组,并在每个字符串的末尾添加一个},除了最后一个.

输出:

String s0 = {U1,U2,U3}
String s1 = {U5,U7}
String s2 = {U4,U6,U8}

Suppose I have the following code:

String s = "{U1,U2,U3},{U5,U7},{U4,U6,U8}";

How can I make this appear like it is below?

String s1 = {U1,U2,U3};
String s2 = {U5,U7};
String s3 = {U4,U6,U8};

The combination in s can be in any form. s1, s2, s3 are different Strings.

解决方案

Here's my code:

public class SplitString {
    public static void main(String[] args) {

        String s ="{U1,U2,U3},{U5,U7},{U4,U6,U8}";
        String[] splitted = s.split("},");

        // add the end brace for every entry except the last
        for (int i=0 ; i < splitted.length-1 ; i++) {
            splitted[i]=splitted[i] + "}";
        }

        // print out the string array
        for (int i=0; i< splitted.length ; i++) {
            System.out.println("String s"+i+" = "+splitted[i]);
        }
    }
}

This splits every time it encounters the two characters },, puts that into the string array "splitted", then loops through the String array and adds a } at the end of every one except the last.

Output:

String s0 = {U1,U2,U3}
String s1 = {U5,U7}
String s2 = {U4,U6,U8}

这篇关于如何将字符串拆分为不同的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆