How to split String on two different chars - java

I already splitted the String value2 on the char "-" and saved its values in a new array as you can see. Now I wanna seperate the String again on the "," and save it again in a new array but it doesn't work. It always just seperates the second name with the number. And overrites the first. So I got in the first Array on [0]: Peter,2 and in [1]: Leo,1
and in the second array just on [0] Leo and on [1] 1.
I know my for loop is wrong and I don't know how to fix it.
final int value = 2;
final String value2 = "Peter,2-Leo,1";
String[] splittedStringOne = new String[value];
String[] splittedStringTwo = new String[splittedStringOne.length*2];
splittedStringOne = value2.split("-");
for(int i=0;i<splittedStringOne.length;i++) {
splittedStringTwo=splittedStringOne[i].split(",");

Assuming that your splittedStringOne contains the right values at index [0] and [1], in your for loop, you will just overwrite the content of splittedStringTwo.
Since String.split(',') returns an array, you should also make splittedStringTwo two dimensional :
String[][] splittedStringTwo = new String[splitedStringOne.length][2];
This should work for the for loop:
for(int i=0;i<splittedStringOne.length;i++) {
splittedStringTwo[i] = splittedStringOne[i].split(",");
}
note that I added [i] to splittedStringTwo

splittedStringTwo has to be 2 dimensional.
String[][] splittedStringTwo = new String[splitedStringOne.length][2];
for(int i =0; i < splittedStringTwo.length; i++)
splittedStringTwo[i] = splittedStringOne[i].split(",");
Or if you dont want a 2 dimensional array:
String[] splittedStringTwo = new String[splittedStringOne.length*2];
for(int i = 0; i < splittedStringTwo.length; i+=2){
String[] split = splittedStringOne[i].split(",");
splittedStringTwo[i] = split[0];
splittedStringTwo[i+1] = split[1];
}
EDIT:
For question in the comments. Try this out, it is not tested but it should work
String[][] splittedStringTwo = new String[splittedStringOne.length*2][2];
for(int i = 0; i < splittedStringTwo.length; i+=2){
String[] split1 = splittedStringOne[i].split(",");
String[] split2 = splittedStringOne[i+1].split(",");
splittedStringTwo[i][0] = split1[0]
splittedStringTwo[i][1] = split2[0];
splittedStringTwo[i+1][0] = split1[1]
splittedStringTwo[i+1][1] = split2[1];
}

You can use arraycopy to copy the result of splittedStringOne[i].split(","); to the correct position of splittedStringTwo
like:
public class ArrayCopyTest {
#Test public void test() {
final String value2 = "Peter,2-Leo,1";
String[] splittedStringOne = value2.split("-");
String[] splittedStringTwo = new String[splittedStringOne.length*2];
for(int i=0;i<splittedStringOne.length;i++) {
// splittedStringTwo = splittedStringOne[i].split(",");
System.arraycopy(splittedStringOne[i].split(","), 0, splittedStringTwo, i * 2, 2);
}
Assert.assertArrayEquals(splittedStringTwo, new String[]{"Peter", "2", "Leo", "1"});
}
}

Related

Split string each element in an array into multiple arrays

I have an array with 2 data fields in each element:
String[] myArr = {"Bob Marley", "Barbara Newton", "John Smith"};
The first and last names and separated by a tab ("\t").
How would I go about splitting them into two arrays, for example:
String[] firstName = {"Bob", "Barbara", "John"};
String[] lastName = {"Marley", "Newton", "Smith"};
I initially tried split("\t") but that didn't work, and I've tried looking up for similar questions here to no avail.
One thing to note, I am not using ArrayList.
Any help would be immensely appreciated. Thank you in advance.
Code snippet:
public static String[] sortNames(String[] info) {
String[] firstName = new String[info.length];
String[] lastName = new String[info.length];
for(int i = 0; i < info.length; i++) {
firstName[i] = info[i].split("\t");
}
return firstName;
}
firstName[i] = info[i].split("\t"); is assign an array to an element,it will cause compile failure.
public static String[] sortNames(String[] info) {
String[] firstName = new String[info.length];
String[] lastName = new String[info.length];
for(int i = 0; i < info.length; i++) {
String[] infos = info[i].split("\t");
firstName[i] = infos[0];
lastName[i] = infos[1];
}
return firstName;//also,you might need to change your return type to String[][] so that both array can be returned
}
You could have your sortNames method return a two-dimensional array:
import java.util.Arrays;
class Main {
public static void main(String[] args) {
String[] myArr = {"Bob Marley", "Barbara Newton", "John Smith"};
String[][] names = sortNames(myArr);
String[] firstNames = names[0];
String[] lastNames = names[1];
System.out.println("names: " + Arrays.deepToString(names));
System.out.println("firstNames: " + Arrays.toString(firstNames));
System.out.println("lastNames: " + Arrays.toString(lastNames));
}
public static String[][] sortNames(String[] info) {
int infoArrLength = info.length;
String[][] names = new String[2][infoArrLength];
for(int i = 0; i < infoArrLength; i++) {
String[] infos = info[i].split("\\s+");
names[0][i] = infos[0];
names[1][i] = infos[1];
}
return names;
}
}
Output:
names: [[Bob, Barbara, John], [Marley, Newton, Smith]]
firstNames: [Bob, Barbara, John]
lastNames: [Marley, Newton, Smith]
String[] myArr = {"Bob Marley", "Barbara Newton", "John Smith"};
String[] firstName = new String[myArr.length];
String[] lastName = new String[myArr.length];
for (int i = 0; i < myArr.length; i++) {
String[] splitString = myArr[i].split("\\s+");
firstName[i] = splitString[0];
lastName[i] = splitString[1];
}
You can simply use java regx to perform the splitting.
\s => A whitespace character, short for [ \t\n\x0b\r\f]
private static void splitArray(String[] arr) {
int len = arr.length;
String[] firstNames = new String[len];
String[] lastNames = new String[len];
for (int i = 0; i < len; ++i) {
String[] names = arr[i].split("\\s+");
firstNames[i] = names[0];
lastNames[i] = names[1];
}
System.out.println(Arrays.deepToString(firstNames));
System.out.println(Arrays.deepToString(lastNames));
}
If I were you, in your case, I'd prefer using javafx.util.Pair to bind the first and last name together as follows and in java 8 using stream will make it cleaner:
private static void splitArrayUsingStream(String[] arr) {
Pair[] pairs = Arrays.stream(arr).map(s -> {
String[] names = s.split("\\s+");
return new Pair<>(names[0], names[1]);
}).collect(Collectors.toList()).toArray(new Pair[arr.length]);
System.out.println(Arrays.deepToString(pairs));
}
These methods will give us output as:
[Bob, Barbara, John]
[Marley, Newton, Smith]
[Bob=Marley, Barbara=Newton, John=Smith]

how to convert an integer string separated by space into an array in JAVA

Suppose I have a string "1 23 40 187 298". This string only contains integers and spaces. How can I convert this string to an integer array, which is [1,23,40,187,298].
this is how I tried
public static void main(String[] args) {
String numbers = "12 1 890 65";
String temp = new String();
int[] ary = new int[4];
int j=0;
for (int i=0;i<numbers.length();i++)
{
if (numbers.charAt(i)!=' ')
temp+=numbers.charAt(i);
if (numbers.charAt(i)==' '){
ary[j]=Integer.parseInt(temp);
j++;
}
}
}
but it doesn't work, please offer some help. Thank you!
You are forgetting about
resetting temp to empty string after you parse it to create place for new digits
that at the end of your string will be no space, so
if (numbers.charAt(i) == ' ') {
ary[j] = Integer.parseInt(temp);
j++;
}
will not be invoked, which means you need invoke
ary[j] = Integer.parseInt(temp);
once again after your loop
But simpler way would be just using split(" ") to create temporary array of tokens and then parse each token to int like
String numbers = "12 1 890 65";
String[] tokens = numbers.split(" ");
int[] ary = new int[tokens.length];
int i = 0;
for (String token : tokens){
ary[i++] = Integer.parseInt(token);
}
which can also be shortened with streams added in Java 8:
String numbers = "12 1 890 65";
int[] array = Stream.of(numbers.split(" "))
.mapToInt(token -> Integer.parseInt(token))
.toArray();
Other approach could be using Scanner and its nextInt() method to return all integers from your input. With assumption that you already know the size of needed array you can simply use
String numbers = "12 1 890 65";
int[] ary = new int[4];
int i = 0;
Scanner sc = new Scanner(numbers);
while(sc.hasNextInt()){
ary[i++] = sc.nextInt();
}
For java 8+ you can use this way:
final Integer[] ints = Arrays.stream(numbers.split(" "))
.map(Integer::parseInt)
.toArray(Integer[]::new);
or, if you need primitive ints, you can use this:
final int[] ints = Arrays.stream(numbers.split(" "))
.mapToInt(Integer::parseInt)
.toArray();
Reset the tmp String to "" after you parse the integer unless you wish to continue to append all the numbers of the String together. There are also alternatives as well - for instance splitting the String into an array on the space characeter, and then parsing the numbers individually
Try this out,
public static void main(String[] args) {
String numbers = "12 1 890 65";
String[] parts = numbers.split(" ");
int[] ary = new int[4];
int element1 = Integer.parseInt(parts[0]);
int element2 = Integer.parseInt(parts[1]);
int element3 = Integer.parseInt(parts[2]);
int element4 = Integer.parseInt(parts[3]);
ary[0] = element1;
ary[1] = element2;
ary[2] = element3;
ary[3] = element4;
for(int i=0; i<4; i++){
System.out.println(ary[i]);
}
}
I met similar question in android development. I want to convert a long string into two array -String array xtokens and int array ytokens.
String result = "201 5 202 8 203 53 204 8";
String[] tokens = result.split(" ");
String[] xtokens = new String[tokens.length/2 + 1];
int[] ytokens = new int[tokens.length/2 + 1];
for(int i = 0, xplace = 0, yplace = 0; i<tokens.length; i++){
String temptoken = new String(tokens[i]);
if(i % 2 == 0){
xtokens[xplace++] = temptoken;
}else {
ytokens[yplace++] = Integer.parseInt(temptoken);
}
}
You can first convert this string into an string array separated by space, then convert it to int array.

populating a java array with a variable

I am trying to populate a java string array with a variable. the variable contains values which I am reading in from a text file. every time a new value is stored in the array the current value is replaced by the new value.
the code below is what i have tried so far.
int n = 0;
String var1 = value;
String array[] = {var1};
String [] array = new String[n];
for (int i =0; i < n; i++) {
array[n++] = value;
}
Java has only fixed sized arrays; dynamically growing "arrays" are realized with List:
List<String> array = new ArrayList<>();
for (int i = 0; i < 42; ++i) {
String s = "" + i;
array.add(s);
}
for (String t : array) {
System.out.println(t);
}
String seven = array.get(7);
int n = array.size();
if (array.isEmpty()) { ... }
// In Java 8:
array.stream().sorted().forEach(System.out::println);
Using (fixed sized) arrays would be cumbersome:
String[] array = new String[];
String[] otherVar = array;
for (int i = 0; i < 42; ++i) {
String s = "" + i;
array = Arrays.copyOf(array, i + 1);
array[i] = s;
}
Here on every step a new array is created, the content of the old array copied.
Also notice that otherVar keeps the initial empty array.
Note that String[] a is the same as String a[]. The latter is only for compatibility to C/C++, and is less readable.
This will add a string indefinitely. When you read all the data from file you have to set isFileNotEnded = false
boolean isFileNotEnded = true;
List<String> array = new ArrayList<>;
while (isFileNotEnded) {
array.add("hello");
//stop here the infinite loop
}

How do I concatenate all string elements of several arrays into one single array?

How do I concatenate, or append, all of the arrays that contain text strings into a single array? From the following code:
String nList[] = {"indonesia", "thailand", "australia"};
int nIndex[] = {100, 220, 100};
String vkList[] = {"wounded", "hurt"};
int vkIndex[] = {309, 430, 550};
String skList[] = {"robbed", "detained"};
int skIndex[] = {120, 225};
String nationality = "";
//System.out.println(nationality);
I want to store all strings of all three string-containing arrays:
String nList[] = {"indonesia", "thailand", "australia"};
String vkList[] = {"wounded", "hurt"};
String skList[] = {"robbed", "detained"};
into a single array, say array1[].
ArrayList<String> temp = new ArrayList<String>();
temp.addAll(Arrays.asList(nList));
temp.addAll(Arrays.asList(vkList));
temp.addAll(Arrays.asList(skList));
String[] result = (String[])temp.toArray();
You can add the content of each array to a temporary List and then convert it's content to a String[].
List<String> temp = new ArrayList<String>();
temp.addAll(Arrays.asList(nList));
temp.addAll(Arrays.asList(vkList));
temp.addAll(Arrays.asList(skList));
String[] result = new String[temp.size()];
for (int i = 0; i < temp.size(); i++) {
result[i] = (String) temp.get(i);
}
Alternatively, you can use Guava's ObjectArrays#concat(T[] first, T[] second, Class< T > type) method, which returns a new array that contains the concatenated contents of two given arrays. For example:
String[] concatTwoArrays = ObjectArrays.concat(nList, vkList, String.class);
String[] concatTheThirdArray = ObjectArrays.concat(concatTwoArrays, skList, String.class);
public static String[] join(String [] ... parms) {
// calculate size of target array
int size = 0;
for (String[] array : parms) {
size += array.length;
}
String[] result = new String[size];
int j = 0;
for (String[] array : parms) {
for (String s : array) {
result[j++] = s;
}
}
return result;
}
Just define your own join method. Found # http://www.rgagnon.com/javadetails/java-0636.html

Using String.split() to access numeric values

i tried myself lot but can't get a solution so i'm asking help.
i have an string String input="---4--5-67--8-9---";
now i need to convert in into an string array which will look like:
String [][]output={{4},{5},{67},{8},{9}};
i tried with split() and
java.util.Arrays.toString("---4--5-67--8-9---".split("-+")
but can't find the desired answer. so what to do?
actually i need the value 4,5,67,8,9.but i'm not sure how to find them. i will treat the values as integer for further processing
String[] numbers = "---4--5-67--8-9---".split("-+");
String[][] result = new String[numbers.length][1];
for (int i = 0; i < numbers.length; i++) {
result[i][0] = numbers[i];
}
Update: to get rid of the initial empty value, you can get a substring of the input, like:
int startIdx = 0;
char[] chars = input.toCharArray();
for (int i = 0; i < chars.length; i ++) {
if (Character.isDigit(chars[i])) {
startIdx = i;
break;
}
}
input = input.substring(startIdx);
(or you can check them for not being empty (String.isEmpty()) when processing them later.)
First, here is the answer to your question. This code will generate a two-dimensional array where each element is an array consisting of a single numeric string.
final String input = "---4--5-67--8-9---";
// desired output: {{4},{5},{67},{8},{9}}
// First step: convert all non-digits to whitespace
// so we can cut it off using trim()
// then split based on white space
final String[] arrayOfStrings =
input.replaceAll("\\D+", " ").trim().split(" ");
// Now create the two-dimensional array with the correct size
final String[][] arrayOfArrays = new String[arrayOfStrings.length][];
// Loop over single-dimension array to initialize the two-dimensional one
for(int i = 0; i < arrayOfStrings.length; i++){
final String item = arrayOfStrings[i];
arrayOfArrays[i] = new String[] { item };
}
System.out.println(Arrays.deepToString(arrayOfArrays));
// Output: [[4], [5], [67], [8], [9]]
However, I think what you really need is an array of Integers or ints, so here is a revised solution:
final String input = "---4--5-67--8-9---";
// Convert all non-digits to whitespace
// so we can cut it off using trim()
// then split based on white space
final String[] arrayOfStrings =
input.replaceAll("\\D+", " ").trim().split(" ");
// Now create an array of Integers and assign the values from the string
final Integer[] arrayOfIntegers = new Integer[arrayOfStrings.length];
for(int i = 0; i < arrayOfStrings.length; i++){
arrayOfIntegers[i] = Integer.valueOf(arrayOfStrings[i]);
}
System.out.println(Arrays.toString(arrayOfIntegers));
// Output: [4, 5, 67, 8, 9]
// Or alternatively an array of ints
final int[] arrayOfInts = new int[arrayOfStrings.length];
for(int i = 0; i < arrayOfStrings.length; i++){
arrayOfInts[i] = Integer.parseInt(arrayOfStrings[i]);
}
System.out.println(Arrays.toString(arrayOfInts));
// Output: [4, 5, 67, 8, 9]
Whether you use the Integer or the int version really depends on whether you want to just do some math (int) or need an object reference (Integer).
String[] result = "---4--5-67--8-9---".split("-+");
int i;
for (i = 0; i < result.length; i++) {
if (result[i].length() > 0) {
System.out.println(result[i]);
}
}
gives me output:
4
5
67
8
9
public class split{
public static void main(String[] argv){
String str="---4--5-67--8-9---";
String[] str_a=str.split("-+");
}
}
This seems to working for me.
Using a regex pattern seems more natural in this case:
public class split {
public static int[] main(String input) {
ArrayList<String> list = new ArrayList() ;
Pattern pattern = Pattern.compile("[0-9]") ;
Matcher matcher = pattern.matcher(input) ;
String match = null ;
while( ( match = matcher.find() ) === true ) {
list.add(match) ;
}
String[] array = list.toArray( new String[ ( list.size() ) ]() ) ;
return array ;
}
}
String input="---4--5-67--8-9---";
Scanner scanner = new Scanner(input).useDelimiter("-+");
List<Integer> numbers = new ArrayList<Integer>();
while(scanner.hasNextInt()) {
numbers.add(scanner.nextInt());
}
Integer[] arrayOfNums = numbers.toArray(new Integer[]{});
System.out.println(Arrays.toString(arrayOfNums));
I thought the following is quite simple, although it uses List and Integer arrays, Its not that an overhead for small strings:
For simplicity, I am returning a single dimension array, but can be easily modified to return an array you want. But from your question, it seems that you just want a list of integers.
import java.util.*;
public class Test {
public static void main(String[] args) throws Throwable {
String input = "---4--5-67--8-9---";
System.out.println(split(input).length); // 5
}
public static Integer[] split(String input) {
String[] output = input.split("\\-+");
List<Integer> intList = new ArrayList<Integer>(output.length);
// iterate to remove empty elements
for(String o : output) {
if(o.length() > 0) {
intList.add(Integer.valueOf(o));
}
}
// convert to array (or could return the list itself
Integer[] ret = new Integer[intList.size()];
return intList.toArray(ret);
}
}
I might be late to the party but I figured I'd give the guava take on this.
String in = "---4--5-67--8-9---";
List<String> list = Lists.newArrayList(Splitter.on("-").omitEmptyStrings().trimResults().split(in));
System.out.println(list);
// prints [4, 5, 67, 8, 9]

Categories