如何拆分数组值并创建单独的数组

时间:2016-10-03 11:13:12

标签: java arrays

以下是在单独的阵列中存储电子邮件和电话的代码如何做到这一点我在使用拆分功能拆分单个单词后,将单独的数据存储电话和电子邮件存在问题

在下面编码电话号码打印三次

 public class SplitDemo {
public static void main(String[] args) {
    String[] s1 = { "9964289813-pradeep@­gmail.com", "9591237001-pramod@g­mail.com",
            "8722922982-nandi@gm­ail.com" };
    String[] temp2;
    for (int i = 0; i < s1.length; i++) {
        String singleWord = s1[i];
        String[] splitArray = singleWord.split("-");
        String[] temp1 = new String[s1.length];
        for (int j = 0; j < temp1.length; j++) {
            temp1[j] = splitArray[0];
        }
        for (int j = 0; j < temp1.length; j++) {
            System.out.println(temp1[j]);
        }
    }
}

}

4 个答案:

答案 0 :(得分:0)

创建两个单独的数组(一个Long []用于存储整数值,第二个String []用于电子邮件值)并初始化

long numArray = new long[s1.length];
String emailArray = new String[s1.length];
for (int i = 0; i < s1.length; i++) {            
    String[] parts = s1[i].split("-");
    numArray[i] = Long.parseLong(parts[0]);  
    emailArray[i] = parts[1];  
}

答案 1 :(得分:0)

我更喜欢arraylist 试试这个

    import java.util.ArrayList;

public class SplitDemo {
public static void main(String[] args) {
    String[] s1 = { "9964289813-pradeep@gmail.com", "9591237001-pramod@gmail.com", "8722922982-nandi@gmail.com" };
ArrayList<String> numberlList= new ArrayList<String>();
ArrayList<String> emailList= new ArrayList<String>();
    for (int i = 0; i < s1.length; i++) {
        String singleWord = s1[i];
numberlList.add(singleWord.substring(0, singleWord.indexOf("-")));
emailList.add(singleWord.substring(singleWord.indexOf("-")));
    }
}
}

答案 2 :(得分:0)

创建2个字符串数组,一个用于电话,另一个用于电子邮件。两者的大小都是s1.length。

在for循环中,将提取的手机添加到手机阵列并将电子邮件提取到电子邮件阵列:

String[] s1 = { "9964289813-pradeep@gmail.com","9591237001pramod@gmail.com","8722922982-nandi@gmail.com" };

String[] phones = new String[s1.length];
String[] emails = new String[s1.length];

for (int i = 0; i < s1.length; i++) {
    String singleWord = s1[i];
    String[] words = singleWord.split("-");
    phones[i] = words[0];
    emails[i] = words[1];
}

答案 3 :(得分:0)

你可以这样做..

public class SplitDemo {
public static void main(String[] args) {
    String[] s1 = { "9964289813-pradeep@gmail.com", "9591237001-pramod@gmail.com", "8722922982-nandi@gmail.com" };
    String[] phoneArr = new String[s1.length];
    String[] emailArr = new String[s1.length];

    for (int i = 0; i < s1.length; i++) {
        String[] splitArray = s1[i].split("-");
        phoneArr[i] = splitArray[0];
        emailArr[i] = splitArray[1];
    }

    // "phoneArr" will contain all Phone Numbers
    // "emailArr" will contain all Email IDs

}

}