Java String to Array - java

I want to evaluate String like "[1,5] [4,5] [10,6]" in in array.
I'm not quite familiar with the Java regex and the syntax.
String game = "[1,5] [4,5] [10,6]"
Pattern splitter = Pattern.compile("\\[|,|\\]");
splitter.matcher(game);
public String [] gameArray = null;
gameArray = splitter.split(game);
I want to to iterate over each pair of array such as : [0][0] => 1; [0][1] => 5

If you put
StringTokenizer st = new StringTokenizer(game, "[,] ");
while (st.hasMoreTokens())
{
currentNumber = Integer.parseInt(st.nextToken());
// fill array with it
}
It should be what you need, if I understood well

For this purpose you need to split your string.
first of all you need to split on space and after that you need to split on ,(comma).and your third step will be remove brackets So at the end you will get you string into array.

Try,
String game = "[1,5] [4,5] [10,6]";
String[] arry=game.substring(1, game.length()-1).split("\\] +\\[");
List<String[]> twoDim=new ArrayList<>();
for (String string : arry) {
String[] twoArr=string.split(",");
twoDim.add(twoArr);
}
String[][] twoArr=twoDim.toArray(new String[0][0]);
System.out.println(twoArr[0][0]); // 1
System.out.println(twoArr[0][1]); // 5

Related

How to convert string of values into array?

I have a string, ie 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17. How do I get each value and convert it into an array? [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]. I can't find any suggestions about this method. Can help? I did try using regex, but it just simply remove ',' and make the string into one long sentence with indistinguishable value. Is it ideal to get value before and after ',' with regex and put it into []?
You could use following solution
String dummy = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17";
String[] dummyArr = dummy.split(",");
Try this to convert string to an array of Integer.
String baseString = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17";
String[] baseArray = baseString.split(",");
int[] myArray = new int[baseArray.length];
for(int i = 0; i < baseArray.length; i++) {
myArray[i] = Integer.parseInt(baseArray[i]);
}
Java provides method Split with regex argument to manipulate strings.
Follow this example:
String strNumbers= "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17";
String[] strNumbersArr= strNumbers.split(",");
You can convert an array of string in array of integer with Streams
int[] numbersArr = Arrays.stream(strNumbersArr).mapToInt(Integer::parseInt).toArray();
Use String.split() and you will get your desired array.
String s1="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17";
String[] mumbers=s1.split(","); //splits the string based on comma
for(String ss:numbers){
System.out.println(ss);
}
See the working Example
String csv = "Apple, Google, Samsung";
String[] elements = csv.split(",");
List<String> fixedLenghtList = Arrays.asList(elements);
ArrayList<String> listOfString = new ArrayList<String>(fixedLenghtList);
//ouput
[Apple, Google, Samsung]
if you want an int array
String s = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17";
String[] split = s.split(",");
int[] result = Arrays.stream(split).mapToInt(Integer::parseInt).toArray();

How to separate variables and arrays out of an expression with StringTokenizer?

I'm trying to separate the arrays and variables from an expression so that I can populate two ArrayLists with either array names or variables. I am using StringTokenizer. I have the expression broken down, but I am having trouble determining which tokens are array names and which are variables.
public void buildSymbols() {
String s = expr; // input from different part of the program
StringTokenizer st = new StringTokenizer(s, "+-*/[]() ");
while(st.hasMoreElements()){
String temp = st.nextToken();
System.out.println(temp);
}
}
I print temp just to make sure that the expression is being separated, but given an expression such as (varx + vary * varz[(vara + varb[(a + b) * 33])]) / 55 I don't know how to tell that varz and varb are array names, while varx, vary, vara, a, and b are variables.
Any ideas how to do this?
I agree wih EJP: The correct solution would be a specific parser. But if you would be content to recognize which delimitter was found by each call to StringTokenizer.nextToken, you can tell StringTokenizer to return also the delimitters. Also, you'll need to retrieve the next delimitter on every current token (as a lookahead). To do that, it's better to store all the tokens in a list:
public void buildSymbols() {
String s = expr; // input from different part of the program
StringTokenizer st = new StringTokenizer(s, "+-*/[]() ", true);
Set<String> delimiters=new HashSet<String>(Arrays.asList(new String[]{"+","-","*","/","[","]","(",")"," "}));
List<Object> tokens=Collections.list(st);
for(int i=0;i<tokens.size();i++){
String temp = tokens.get(i).toString();
if (delimiters.contains(temp))
{
// It is a delimiter
}
else
{
// It is a term
boolean isAnArray=(isNextTokenAnOpenBracket(tokens, i));
...
}
System.out.println(temp);
}
}
private boolean isNextTokenAnOpenBracket(List<Object> tokens, int currentIndex)
{
return (currentIndex < tokens.size() && "[".equals(tokens.get(1 + currentIndex)));
}
Try the String .split() method. It is an alternative to string tokenizer. You can split a string into an array of smaller strings split by a delimiter, just like StringTokenizer. However, you could do it two separate times, the first being with brackets, and the second with the other symbols. Then you know that the last index of your String arrays are the names of Arrays!
String s = expr;
String[] brackSplit = s.split("\\[");
for (String str : brackSplit) {
String[] finalSplit = str.split("*+-/()");
//finalSplit[finalSplit.length - 1] = Array Name!
}
NOTE: StringTokenizer is becoming deprecated with the new version of Java. The string split() method has become the new "recommended" way of splitting strings by delimiters.

String into char on 2D array (java)

I am trying to fill a 2D char array with 5 words. Each string must be split into single characters and fill one row of the array.
String str = "hello";
char[][] words = new char[10][5];
words[][] = str.toCharArray();
My error is at the 3rd line I don't know how to split the string "hello" into chars and fill only the 1st row of the 2-dimensional array
If you want the array to fill the first row, just asign it to the first row:
words[0] = str.toCharArray();
Since this will create a new array in the array, you should change the instantiation of words to this:
char[][] words = new char[5][];
Java has a String class. Make use of it.
Very little is known of what you want with it. But it also has a List class which I'd recommend as well. For this case, I'd recommend the ArrayList implementation.
Now onto the problem at hand, how would this code look now?
List<String> words = new ArrayList<>();
words.add("hello");
words.add("hello2");
words.add("hello3");
words.add("hello4");
words.add("hello5");
for (String s : words) {
System.out.println(s);
}
For your case if you are stuck with using arrays.
String str="hello";
char[][] words = new char[5][];
words[][] = str.toCharArray();
Use something along the line of
String str = "hello";
char[][] words = new char[5][];
words[0] = str.toCharArray();
for (int i = 0; i < 5; i++) {
System.out.println(words[i]);
}
However, why invent the wheel again? There are cases however, more can be read on the subject here.
Array versus List<T>: When to use which?

Java, How to convert a string into an Array

I've got a string, for example:
String code = new String("[199, 56, 120]")
My goal is to create and Array that contains only the numbers inside the [] and beetween commas;
In this case it would be for example:
array[0] = 199
array[1] = 56
array[2] = 120
Is possible to do something like this??
Thanks in advance.
You just need to use the split function.
Skip the [ and the ] and you can do something like this:
String input = "199 56 120";
String[] array = input.split(" ");
If you really want [ and the ] then you can use something like
input.replace("[", "");
input.replace("]", "");
To strip the string before you split it.
Edit
It doesn't matter what the format is or what the numbers are or how many they are, you simply edit the split definition according to the format, so if you're case is , then you simply use that as the split parameter.
String input = "[number, number, number]";
String sep = ", ";
String fixedInput = input.replace("[", "").replace("]", "");
String[] array = fixedInput.split(sep);
// array[0] contains first number.
// array[1] contains second number.
If you want an int[] array then you could do something like this:
int[] intArray = new int[array.length];
for(int i = 0; i < array.length; i++)
{
intArray[i] = Integer.parseInt(array[i]);
}
If you want a one-line solution:
String[] array = code.replaceAll("[^\\d ]", "").split(" ");
The in-line call to replaceAll() removes non-digits/spaces.

Convert String elements to Array

I have a String :
str="[a],[b],[c]";
How can I convert str to array in Java (Android):
array[0] -> a
array[1] -> b
array[2] -> c
EDIT:
and what about multidimensinal array? str="[["a1","a2","a3"],["b1","b2","b3"]]";
try
String str="[a],[b],[c]";
str= str.replaceAll("\\]|\\[", "");
String[] arr= str.split(",");
===========================================
update
converting multi dimension array to single dimension is already answered in SO please check change multidimensional array to single array
just copied the solution
public static String[] flatten(String[][] data) {
List<String> toReturn = new ArrayList<String>();
for (String[] sublist : Arrays.asList(data)) {
for (String elem : sublist) {
toReturn.add(elem);
}
}
return toReturn.toArray(new String[0]);
}
You can use following way.
String Vstr = "[a],[b],[c]";
String[] array = Vstr.replaceAll("\\]|\\[", "").split(",");
You would need to process your string and build your array. You could either take a look at .split(String regex) (which might require you to do some more processing to clean the string) or else, use a regular expression and do as follows:
Use a regex like so: \[([^]]+?)\]. This will seek out characters in between square brackets and put them into a group.
Use the .find() method available from the Matcher class and iterate over the matches. Put everything into a list so that you can put in as many hits as you need.
If you really need the result to be in an array, use the .toArray() method.
Take a look at String.split() method
An alternative to the regex and what npinti, i think, is talking about:
String myStrg = "[a],[b],[c]";
int numCommas = 0;
for( int i = 0; i < myStrg.length(); i++ )
{
// Count commas
if( myStrg.charAt(i) == ',' )
{
numCommas++;
}
}
// Initialize array
myArry = new String[numCommas];
myArry = myStrg.split(",");
// Loop through and print contents of array
for( String arryStrg: myArry )
{
System.out.println( arryStrg );
}
Try this code.
String str="[a],[b],[c]";
str= str.replaceAll("\\]|\\[", "");
String[] arr= str.split(",");

Categories