简体   繁体   中英

How would I separate one value of an array (for the entire array) into alphabetic and numeric characters, and then into separate arrays? (Java)

I've been struggling to find an answer to my specific problem here. I understand that I can use regex to separate array values, but they both don't seem to work and I can't figure out how to get the two values separately. Thanks!

Here's my code without any separation of arr :

package boomaa;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;
import java.lang.*;

public class Solution{
    public static void main(String[] args) throws FileNotFoundException {
        Scanner sc = new Scanner(new File("A.txt"));
        List<String> lines = new ArrayList<String>();
        while (sc.hasNextLine()) {
          lines.add(sc.nextLine());
        }

        String[] arr = lines.toArray(new String[0]);
        System.out.println(Arrays.toString(arr));
        for (int i = 1;i<arr.length;i++) {
            System.out.println(arr[i]);
        }
    }
}

My input is formatted like this:

3
1 CS
2 CS
1 SS

If the numbers and characters are separated by a space, simply iterate over the array and use the String method split to split at the space.

Scanner sc = new Scanner(new File("A.txt"));
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine()) {
   lines.add(sc.nextLine());
}

String[] numbers = new String[lines.size()];
String[] characters = new String[lines.size()];
for (int i = 0; i < lines.size(); i++) {
    String[] components = lines.get(i).split(" ");
    numbers[i] = components[0];
    characters[i] = components[1];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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