简体   繁体   中英

Edit string array and convert it to 2D char array

I start with an array of strings formatted useful.useless . I need to trim out the .useless part, and then put the useful part in a 2D char array.

I see a way that involves creating a second string array containing only the useful part, and then converting that to a 2D char array, but there is probably a more effective way.

However, I don't know how to convert string array to 2D char array

public static void main (String[]args){
    
    // this here is just to create an array so the example runs
    String in = "useful1.useless1,useful2.useless2,useful3.useless3,";
    String[] strArray = null; 
    strArray = in.split(",");
    
    /*the array of strings is thus
    [useful1.useless1, useful2.useless2, useful3.useless3]
    */
    
    char [][] charArray = new char [strArray.length][];
    
    /* trim from the . so only useful part remains
    then put in 2d char array, which should look like
    
    [u,s,e,f,u,l,1]
    [u,s,e,f,u,l,2]
    [u,s,e,f,u,l,3]
    
    the array will be a ragged array
    */

}

You need to populate charArray at each index, with the array of characters of the desired substring of strArray at the corresponding index. You can do it as shown below:

for (int i = 0; i < strArray.length; i++)
    charArray[i] = strArray[i].substring(0, strArray[i].indexOf('.')).toCharArray();

Demo:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        // this here is just to create an array so the example runs
        String in = "useful1.useless1,useful2.useless2,useful3.useless3,";
        String[] strArray = in.split(",");

        /*
         * the array of strings is thus [useful1.useless1, useful2.useless2,
         * useful3.useless3]
         */

        char[][] charArray = new char[strArray.length][];
        for (int i = 0; i < strArray.length; i++)
            charArray[i] = strArray[i].substring(0, strArray[i].indexOf('.')).toCharArray();

        // Display
        for (char[] row : charArray)
            System.out.println(Arrays.toString(row));
    }
}

Output:

[u, s, e, f, u, l, 1]
[u, s, e, f, u, l, 2]
[u, s, e, f, u, l, 3]

Stream the strings:

  • use regex to “remove” the useless part
  • convert the ”useful” String to a char[]
  • collect all char[] into a char[][]

Voila:

char[][] usefulChars = Arrays.stream(strArray)
  .map(s -> s.replaceAll("\\..*", ""))
  .map(String::toCharArray)
  .toArray(char[][]::new);

See live demo .

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