Split string each element in an array into multiple arrays - java

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]

Related

How can I split string elements of an array and add them to another?

Using an array list of names, I am trying to split the first names and surnames using a for loop. The code works but when splitting the names using a substring it goes from 0-x (x being the space between the names) but it reads from 0 each time and adds each name multiple times until it completes. How can I run it from the next element each time to skip the name previously split and added?
public static void main(String[] args) {
String [] name_list = {"lee momo", "michael jesus", "kim danger", "dean habbo"};
ArrayList<String> firstNames = new ArrayList<String>();
ArrayList<String> surnames = new ArrayList<String>();
for(int i = 0; i < name_list.length; i++){
int x = name_list[i].indexOf(" ");
String firstName = name_list[i].substring(0, x);
firstNames.add(firstName);
for(int j = 0; j < name_list.length; j++){
int y = name_list[i].indexOf(" ");
String surname = name_list[i].substring(x);
surnames.add(surname);
}
System.out.println(firstNames.toString());
System.out.println(surnames.toString());
}
}
For example the output of first names is like this:
lee
lee, michael
lee, michael, kim
lee, michael, kim, dean
Fix
You need only one loop, to extract both
String[] name_list = {"lee momo", "michael jesus", "kim danger", "dean habbo"};
ArrayList<String> firstNames = new ArrayList<>();
ArrayList<String> surnames = new ArrayList<>();
for (int i = 0; i < name_list.length; i++) {
int x = name_list[i].indexOf(" ");
String firstName = name_list[i].substring(0, x);
firstNames.add(firstName);
String surname = name_list[i].substring(x + 1);
surnames.add(surname);
}
System.out.println(firstNames); // [lee, michael, kim, dean]
System.out.println(surnames); // [momo, jesus, danger, habbo]
Improve
use String.split()
use a for each loop
for (String s : name_list) {
String[] parts = s.split("\\s+");
firstNames.add(parts[0]);
surnames.add(parts[1]);
}
for(int i = 0; i < name_list.length; i++){
String[] split_name = name_list[i].split(" ");
int x = name_list[i].indexOf(" ");
String firstName = name_list[i].substring(0,x);
firstNames.add(firstName);
//indexOf would be useful when surname has space separated more tahn
// one owrd
String surname = name_list[i].substring(x+1);
surnames.add(surname);
}
for(int i=0; i<firstNames.size(); ++i){
System.out.println(firstNames.get(i));
System.out.println(surnames.get(i));
}

Way to transfer the data in one array to two arrays?

https://i.stack.imgur.com/Daxvo.png
So this is my assignment. I was able to split the input using the split() method, which created an array, splitArray. But the problem is, I don't know how to transfer the contents of the splitArray to the phoneNumberVec and nameVec array.
splitArray[] data:
Joe
123-5432
Linda
983-4123
Frank
867-5309
Is there a way to put the names into one array and the numbers in another?
I hope I was clear on my question, I'm new to this whole thing! Thank you!
This is pretty simple. I think it's more comfortable to use Scanner instead of string split:
public static void main(String[] args) {
String contactList = "3 Joe 123-5432 Linda 983-41-23 Frank 867-5309";
String contactName = "Frank";
System.out.println(getPhoneNumber(contactList, contactName));
}
public static String getPhoneNumber(String contactList, String contactName) {
try (Scanner scan = new Scanner(contactList)) {
int N = scan.nextInt();
String[] nameVec = new String[N];
String[] phoneNumberVec = new String[N];
for (int i = 0; i < N; i++) {
nameVec[i] = scan.next();
phoneNumberVec[i] = scan.next();
}
return getPhoneNumber(nameVec, phoneNumberVec, contactName, N);
}
}
public static String getPhoneNumber(String[] nameVec, String[] phoneNumberVec, String contactName, int arraySize) {
for (int i = 0; i < arraySize; i++)
if (nameVec[i].equals(contactName))
return phoneNumberVec[i];
return "<not found>";
}

How To Add space in a string based on a string array if the string is present

How To Add space in a string based on a string array if the string is present in java.
my problem is:
//input string
//314562173583721321376
//array of string
//{3 ,314,49, 90234,56217358, 14,3721,376,4, 789 }
//output
//3 314 56217358 3721 376
String myString = "314562173583721321376";
String inputArray[] = new String[] {"3" ,"314","49", "90234","56217358", "14","3721","376","4"," 789" };
this should generate this output
3 314 56217358 3721 376
this code can be used to shortlist the numbers but how do we add spaces.
ArrayList<String> newArrayWithOnlyTheContainedNums = new ArrayList<>();
for (int i =0 ;i< inputArray.length - 1 ;i++ ){
if(myNum.contains(inputArray[i]) ){
newArrayWithOnlyTheContainedNums.add(inputArray[i]);
}
}
Try this:
class Main
{
public static void main(String args[])
{
String date = "",neawe = "";
String myNum = "314562173583721321376";
String inputArray[] = new String[] {"3" ,"314","49", "90234","56217358", "14","3721","376","4"," 789" };
ArrayList<String> newArrayWithOnlyTheContainedNums = new ArrayList<>();
for (int i =0 ;i< inputArray.length - 1 ;i++ ){
if(myNum.contains(inputArray[i]) && inputArray[i].length() >= 3){
newArrayWithOnlyTheContainedNums.add(inputArray[i]);
}
}
for (int i =0 ;i< newArrayWithOnlyTheContainedNums.size() ;i++ ){
date = String.join(" ",newArrayWithOnlyTheContainedNums);
}
System.out.println("date is = "+ date);
}
}
Here you have one possible approach:
public static void main(String[] args) {
String myString = "314562173583721321376";
String[] inputArray = new String[]{"3", "314", "49", "90234", "56217358", "14", "3721", "376", "4", " 789"};
ArrayList<String> resultArray = new ArrayList<>();
for (int i =0 ;i< inputArray.length - 1 ;i++ ){
String num = inputArray[i];
int matchIndex = myString.indexOf(inputArray[i]);
if(matchIndex != -1){
resultArray.add(num);
myString = myString.substring(matchIndex);
}
}
resultArray.forEach(s -> System.out.print(s + " "));
}

How to split String on two different chars

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"});
}
}

Splitting string into different arrays of types using regex

What's the easiest and most effective way to spit a string into different arrays of types? Example:
String[] textArr;
String[] numbersArr;
and if possible a String[] doubleArr and a String[] dateArrayz
//the string I want to split
String splitMe = "Tinus has 99 issues and has to pay $2200.50 for 26 on 2016/10/10";
After it's split it should be
String[] textArr = ["Tinus","has","issues","and","to","pay","for","on"];
String[] numbersArr = ["99","26"];
String[] doubleArr = ["2200.50"];
String[] dateArr = ["2016/10/10"];
I might opt for just splitting the input string by space, and then using a pattern match to check each entry to determine where it belongs:
String splitMe = "Tinus has 99 issues and has to pay $2200.50 for 26 on 2016/10/10";
String[] parts = splitMe.split(" ");
List<String> textList = new ArrayList<>();
List<String> numbersList = new ArrayList<>();
List<String> currencyList = new ArrayList<>();
List<String> dateList = new ArrayList<>();
for (String part : parts) {
if (part.matches("\\d*")) {
numbersList.add(part);
}
else if (part.matches("\\$\\d*\\.\\d*")) {
currencyList.add(part);
}
else if (part.matches("\\d{4}/\\d{2}/\\d{2}")) {
dateList.add(part);
}
else {
textList.add(part);
}
}
I didn't attempt to formally extract a double from the currency. And I also chose to use lists rather than arrays to store the various terms, because this will scale better. I will leave it up to you to fill in the details.
You can try something like this:
String splitMe = "Tinus has 99 issues and has to pay $2200.50 for 26 on 2016/10/10";
String[] splitArray = splitMe.split(" ");
System.out.println("splitArray: " + Arrays.toString(splitArray));
String[] tmp = new String[splitArray.length];
int i = 0;
for (String s : splitArray) {
if (s.matches("[A-Za-z]+")) {
tmp[i] = s;
i++;
}
}
String[] textArr = new String[i];
for (int j = 0; j < textArr.length; j++) {
textArr[j] = tmp[j];
}
tmp = new String[splitArray.length];
i = 0;
for (String s : splitArray) {
if (s.matches("[0-9]+")) {
tmp[i] = s;
i++;
}
}
String[] numbersArr = new String[i];
for (int j = 0; j < numbersArr.length; j++) {
numbersArr[j] = tmp[j];
}
tmp = new String[splitArray.length];
i = 0;
for (String s : splitArray) {
if (s.matches("\\$[0-9]+\\.[0-9]+")) {
tmp[i] = s;
i++;
}
}
String[] doubleArr = new String[i];
for (int j = 0; j < doubleArr.length; j++) {
doubleArr[j] = tmp[j];
}
tmp = new String[splitArray.length];
i = 0;
for (String s : splitArray) {
if (s.matches("[0-9]+/[0-9]+/[0-9]+")) {
tmp[i] = s;
i++;
}
}
String[] dateArr = new String[i];
for (int j = 0; j < dateArr.length; j++) {
dateArr[j] = tmp[j];
}
System.out.println("textArr: " + Arrays.toString(textArr));
System.out.println("numbersArr: " + Arrays.toString(numbersArr));
System.out.println("doubleArr: " + Arrays.toString(doubleArr));
System.out.println("dateArr: " + Arrays.toString(dateArr));
Please note that the regex used are not ideal but they work for your case. I used arrays because I thought it is a strict requirement. You can use lists as well which is better.

Categories