Home > Back-end >  How to use an array to substract part of a continuous sentences?
How to use an array to substract part of a continuous sentences?

Time:11-06

For example,I will like to type something like:

CanadaTdawd,USATdawh,BrizilT82he,EnglandT713, so on

need to use 2d array to store them so I plan to using for loop to store all values in[][],then use print() for the same group of letters.But stucks in following steps..

print out will need be like:

Canada

USA

Brizil

any way to store each of the letters from the word like Canada,USA,Brizil in string[][]?

should only print out letters of substring before T or between comma and T for the second,and third one and so on.

Such as

string[0][0]=C;

string[0][1]=a;

string[0][2]=n;

so on.

string[1][0]=U;

string[1][1]=S;

string[1][2]=A;

And then I could use for loop to combine them together,I know how to use split to do it for the 1D array,but dont know there is anyway to do it in 2D array. So confused need help!

CodePudding user response:

The list of countries may be retrieved using split by the delimiter expression like this: "(T\\w ,?)" - T followed by a sequence of alphanumeric chars with optional comma.
Then each word may be "split" to letters (actually to 1-char strings).

Stream API should be used here like this:

String s = "CanadaTdawd,USATdawh,BrizilT82he,EnglandT713";
String[][] result = Arrays.stream(s.split("(T\\w ,?)")) // Stream<String> countries
    .map(country -> country.split("")) // Stream<String[]> letters
    .toArray(String[][]::new); // resulting jagged array

System.out.println(Arrays.deepToString(result));

Output:

[[C, a, n, a, d, a], [U, S, A], [B, r, i, z, i, l], [E, n, g, l, a, n, d]]

Similarly, a jagged char[][] array may be created:

char[][] chars = Arrays.stream(s.split("(T\\w ,?)")) // Stream<String> countries
    .map(String::toCharArray) // Stream<char[]> letters
    .toArray(char[][]::new); // resulting jagged array
System.out.println(Arrays.deepToString(chars));

Output (here chars are printed, not strings):

[[C, a, n, a, d, a], [U, S, A], [B, r, i, z, i, l], [E, n, g, l, a, n, d]]

CodePudding user response:

For this your ideal solution would be character array

char [][];

you can break down a String to char array in many ways

  1. Using charAt(). Look at the documentation https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#charAt(int)
  2. Using toCharArray(). Try this https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#toCharArray()
  • Related