How to convert string of values into array? - java

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();

Related

Extracting integer from a string

Hi I am just starting to learn java and i am stuck on a problem.
The problem states that if we have a string S
S = "123:456:789"
We have to extract the numbers 123 ,456,789 separately and store them in different variables such as
int a=123
Int b=456
Int c=789
How can we do that?
You can split them by the : character and then save parse the Strings and save them in an array as follows:
String S = "123:456:789";
String[] arr = S.split(":");
int[] integers = new int[arr.length];
for(int i = 0; i < arr.length; i++)
integers[i] = Integer.parseInt(arr[i]);
You can split the string based on a delimiter into a string array. Once you have the string array you can access each array's element to get the specific values.
String S = "123:456:789"
String[] example = S.split(":");
Source: https://javarevisited.blogspot.com/2017/01/how-to-split-string-based-on-delimiter-in-java.html
Look at the method split() in String, and into Integer.parseInt().
You also need to look into Regular Expressions

How to parse first 6 strings of a line

I have a line from a dataset like this : vhigh,vhigh,2,2,small,low,unacc`
and I am trying to read the first 6 strings
vhigh,vhigh,2,2,small,low
to a String array and the last String
unacc
to another String variable.
I tried to use String[] arr = line.split(",") and then doString var = arr[5] but this also stored the last string to the array.
Does anyone has another idea ?
You can use String.split() to split input into an array, Arrays.copyOfRange() to copy first elements into new array, and String.join() to join those parts to a new String.
String input = "vhigh,vhigh,2,2,small,low,unacc";
String[] inputParts = input.split(",");
String firstSix = String.join(",", Arrays.copyOfRange(inputParts, 0, 6));
String last = inputParts[6];
System.out.println(firstSix);
System.out.println(last);

java string [] array remove special character

how to remove "," in below string specified at s[0,2] location(818001,818002)(151515,151515) and store again to string []
String[] s = {"818001,818002","121212","151515,151515"};
You should explain more detailed your problem.
I think what you want is this:
s = '(818001,818002)(151515,151515)' //the string you have.
s = s.replace(')(',',').replace('(','').replace(')','');// output "818001,818002,151515,151515"
final_string = s.split(','); //output (4) ["818001", "818002", "151515", "151515"]
If you need to remove a comma (or any other char for that matter) in your String array indices the simplest is to iterate through the array and use String.replace():
String[] s = {"818001,818002","121212","151515,151515"};
for(int i=0; i<s.length; i++) {
s[i] = s[i].replace(",", "");
}
System.out.print(Arrays.toString(s)); // [818001818002, 121212, 151515151515]

Java String to Array

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

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