Converting a string[] into a string then split into an array - java

I need help creating a loop which splits strings. So far I have the code below.
System.out.println("*FILE HAS BEEN LOCATED*");
System.out.println("*File contains: \n");
List<String> lines = new ArrayList<String>();
while (scan.hasNextLine())
{
lines.add(scan.nextLine());
}
String[] arr = lines.toArray(new String[0]);
String str_array = Arrays.toString(arr);
String[] arraysplit;
arraysplit = str_array.split(":");
for (int i=0; i<arraysplit.length; i++)
{
arraysplit[i] = arr[i].trim();
System.out.println(arr[i]);
}
an example of one of the strings would be
Firstname : Lastname : age
I want it to split the string into another array that looks like:
Firstname
Lastname
age
I still encounter an error when running the code, it seems as though when I convert the array to a string, it puts commas in the string and therefore it causes problems as I'm trying to split the string on : not ,
image:

Issue : you are using the old array arr to display values and arraysplit will have resultant values of split method so you need to apply trim() on arraysplit's elements and assign back the elements to same indexes
String[] arraysplit;
arraysplit = str_array.split(":");
for (int i=0; i<arraysplit.length; i++)
{
arraysplit[i] = arraysplit[i].trim();
// ^^^^^^^^^^^^ has values with spaces
System.out.println(arr[i]);
}
System.out.println(arraysplit[i]);
To simplify solution without (list to array and array to string complication)
1.) Create array of length as sizeOfList * 3
2.) split the list element using \\s*:\\s*
3.) Use array copy with jas index of resultant array to keep the track of the array index
String result[] = new String [lines.size()*3];
int j=0;
for (int i=0; i<lines.size(); i++)
{
System.arraycopy(lines.get(0).split("\\s*:\\s*"), 0, result, j, 3);
j+=3;
}
System.out.println(Arrays.toString(result));
You can use regex str_array.split("\\s*:\\s*"); where
\\s*:\\s* : \\s* mean zero or more spaces then : character then zero or more spaces
arraysplit = str_array.split("\\s*:\\s*");
// just use values of arraysplit

Split using this regex \s*:\s*
String[] arraysplit = str_array.split("\\s*:\\s*");
details :
\s* zero or more spaces
followed by lateral character :
followed by \s* zero or more spaces
regex demo

Related

How should I map a function onto a string array in java?

I want to split a string and trim each word in the newly established array. Is there a simple (functional) way in Java how to do it as a one liner without the use of a cycle?
String[] stringarray = inputstring.split(";");
for (int i = 0; i < stringarray.length; i++) {
stringarray[i] = stringarray[i].trim();
}
EDIT: corrected the cycle (Andreas' comment)
You can do it in the following way:
String[] stringarray = inputstring.trim().split("\\s*;\\s*");
Explanation of the regex:
\s* is zero or more times whitespace
\s*;\s* specifies zero or more times whitespace followed by ; which may be followed by zero or more times whitespace
With streams you could do this:
String[] stringarray = Arrays.stream(inputstring.split(";"))
.map(String::trim)
.toArray(String[]::new);
This may not be pure Array solution but a java 8 solution:
String str = " string1 ;string2 ;string3 ;string4;";
String [] s = Arrays.stream(str.split(";")).map(String::trim).collect(Collectors.toList()).toArray(new String[]{});
System.out.println(Arrays.toString(s));
First convert the array to a stream (using the Arrays class), then use the map function, then convert back to array.
https://mkyong.com/java8/java-8-how-to-convert-a-stream-to-array/

How to split and store a string with dots and spaces into a string array including that spaces and dots [duplicate]

This question already has answers here:
Split string based on regex but keep delimiters
(3 answers)
Closed 4 years ago.
I know the split can be done with split functionality of java. I did that like in the below code
String[] sArr = name.split("[\\s.]+");
String newStr = "";
for (int i = 0; i < sArr.length; i++){
newStr = newStr + " " + mymethod(sArr[i]);
}
What i actually want to do is all the words in the string must pass through mymethod and reform the string. But on reforming i dont want to loss the dots and spaces which is actually there. For example Mr. John will remove the dot after reforming and would change in to Mr John which i don't want. So how to reform my string without losing anything in that actual string, but also each word to pass through mymethod also. Thanks in advance!
Iterate over String using any loop char by char and find for . and space char, Then by using substring() method split Original string by storing index.
Code:-
List<String> arr=new ArrayList<String>(); // Array to hold splitted tokens
String str="Mr. John abc. def";
int strt=0;
int end=0;
for (int i = 0; i < str.length(); i++) { //Iterate over Original String
if (str.charAt(i)=='.') // Match . character
{
end=i;
arr.add(str.substring(strt,end));
arr.add(str.charAt(i)+"");
strt=i+1;
}
if (str.charAt(i)==' ') // Match space character
{
end=i;
if (strt!=end) // check if space is not just after . character
arr.add(str.substring(strt,end));
strt=i+1;
}
}
System.out.println(arr);

How to split a string by comma followed by a colon in java?

I'm a java newbie and I'm curious to know how to split a string that starts with a comma and gets followed by a colon towards the end.
An example of such string would be?
-10,3,15,4:38
5,15,8,2:8
Could it be like this?
sections = line.split(",");
tokens = sections[3].split(":");
or is it even possible to split line which the file is read into twice?
tokens = line.split(",");
tokens = line.split(":");
I also tried this but it gave me an ArrayOutOfBound error
tokens = line.split("[,:]");
Any contribution would be appreciated.
use a regular expression in the split section such as
line.split(",|;");
Haven't tested it but I think you get the idea.
You can also do it this way, if you want it for a general case, the method basically takes in the string array, splits each string at each index in the array and adds them to an ArrayList. You can try it, it works.
public static void splitStrings(String[] str){
String[] temp1 =null;//initialize temp array
List<String> itemList = new ArrayList<String>();
for(int i=0;i<str.length;i++){
temp1=str[i].split(",|:");
for (String item : temp1) {
itemList.add(item);
}
//Only print the final result of collection once iteration has ended
if(i==str.length-1){
System.out.println(itemList);
}
}
I am not sure if I totally understand your question correctly. But if you first want to split by , and then by :, you can call split() function twice
String[] str = {"-10,3,15,4:38", "5,15,8,2:8"};
for (String s: str) {
String[] temp = s.split(",")[3].split(":");
System.out.println(temp[0] + " " + temp[1]);
}
Output:
4 38
2 8

First element in array of strings is empty when using split

So I'm trying to read some numbers from a file and put them into an array. I've been reading about people having problems with whitespace, so using trim, I did it like this:
String[] tokens = new String[length];
for(int i = 0; i<length;i++){
String line = fileReader.nextLine();
line = line.trim();
tokens = line.split("");
}
But the first element this array (token[0]) becomes empty. Am I using the split function wrong?
You need to tell the split method what character it should split on. Try this:
tokens = line.split(" "); //split on a space character
tokens = line.split(" ");
You forgot whitespace.

Java - how do you search through an array of strings to remove all the quotation marks?

Let's say, for example, I have an array of 5 elements, each of them being a string. One of the strings, however, has quotation marks around it, which I would like to remove automatically. Is there a function for doing this easily?
*remove the quotation marks, that is. Not the entire string from the array
Remove all quotes from a string:
String input = "foo \"bar\" baz";
String output = input.replace("\"", "");
http://ideone.com/RFZZq
Because the String would be in array, you would have to loop through the entire array, and for each element, check to see if quotations marks were found. If they were found, they will be removed by using String's replace method. Example below:
String[] myArray = {"This", "may", "have", "a", "\"Quotation\"", "In", "It"};
for (int i = 0; i < myArray.length; i++) {
if (myArray[i].contains("\"")) {
myArray[i] = myArray[i].replace("\"", "");
}
}
Above mentioned ways are good but you can also do that through this code
String s1 = "bhb/vgvg/vvv";
String fr[] = s1.split("/");
for (String string : fr)
{
System.out.print(string);
}
It will also remove all the quotes from a string

Categories