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.
Related
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
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
I have made this method to take in a file.txt and transfer its elements into an array list.
My problem is, I dont want to transfer a whole line into one string. I want to take each element on the line as string.
public ArrayList<String> readData() throws IOException {
FileReader pp=new FileReader(filename);
BufferedReader nn=new BufferedReader(pp);
ArrayList<String> data=new ArrayList<String>();
String line;
while((line=nn.readLine()) != null){
data.add(line);
}
xoxo.close();
return data;
}
is it possible ?
What about reading the lines, but splitting each line into the single words?
while ((line = nn.readLine()) != null) {
for (String word : line.split(" ")) {
data.add(line);
}
}
The method split(" ") in this example will split the line on each whitespace " " and put the single words into an array.
In case the words in the file are separated by another character (like a comma for example) you can use that too in split():
line.split(",");
If I may, here is a somewhat easier way to read a text file:
Scanner scanner = new Scanner(filename);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
for (String word : line.split(" ")) {
data.add(word);
}
}
Well not easier but shorter :)
And one last advice: if you give your variables a more.. readable name like bufferedReader instead of naming them all nn, pp, xoxo you might have less problems when the code grows more and more complex later on
Use split function for String.
String line = "This is line";
String [] a = line.split("\\s");// \\s is regular expression for space
a[0] = This
a[1] = is
a[2] = line
If by 'Element' you mean each word, then simply changing
line = nn.readLine()
to
line = nn.read()
should fix your problem, as the read method will take in every character it reads until it hits a space character in which it will return the processed characters. However if by element you mean each character then the problem is much harder. You will need to read each word and split that string up using any of the various functions Java provides.
I'm trying to write a code that uses a scanner to input a list of words, all in one string, then alphabetizer each individual word. What I'm getting is just the first word alphabetized by letter, how can i fix this?
the code:
else if(answer.equals("new"))
{
System.out.println("Enter words, separated by commas and spaces.");
String input= scanner.next();
char[] words= input.toCharArray();
Arrays.sort(words);
String sorted= new String(words);
System.out.println(sorted);
}
Result: " ,ahy "
You're reading in a String via scanner.next() and then breaking that String up into characters. So, as you said, it's sorting the single-string by characters via input.toCharArray(). What you need to do is read in all of the words and add them to a String []. After all of the words have been added, use Arrays.sort(yourStringArray) to sort them. See comments for answers to your following questions.
You'll need to split your string into words instead of characters. One option is using String.split. Afterwards, you can join those words back into a single string:
System.out.println("Enter words, separated by commas and spaces.");
String input = scanner.nextLine();
String[] words = input.split(",| ");
Arrays.sort(words);
StringBuilder sb = new StringBuilder();
sb.append(words[0]);
for (int i = 1; i < words.length; i++) {
sb.append(" ");
sb.append(words[i]);
}
String sorted = sb.toString();
System.out.println(sorted);
Note that by default, capital letters are sorted before lowercase. If that's a problem, see this question.
I got a string with a bunch of numbers separated by "," in the following form :
1.2223232323232323,74.00
I want them into a String [], but I only need the number to the right of the comma. (74.00). The list have abouth 10,000 different lines like the one above. Right now I'm using String.split(",") which gives me :
System.out.println(String[1]) =
1.2223232323232323
74.00
Why does it not split into two diefferent indexds? I thought it should be like this on split :
System.out.println(String[1]) = 1.2223232323232323
System.out.println(String[2]) = 74.00
But, on String[] array = string.split (",") produces one index with both values separated by newline.
And I only need 74.00 I assume I need to use a REGEX, which is kind of greek to me. Could someone help me out :)?
If it's in a file:
Scanner sc = new Scanner(new File("..."));
sc.useDelimiter("(\r?\n)?.*?,");
while (sc.hasNext())
System.out.println(sc.next());
If it's all one giant string, separated by new-lines:
String oneGiantString = "1.22,74.00\n1.22,74.00\n1.22,74.00";
Scanner sc = new Scanner(oneGiantString);
sc.useDelimiter("(\r?\n)?.*?,");
while (sc.hasNext())
System.out.println(sc.next());
If it's just a single string for each:
String line = "1.2223232323232323,74.00";
System.out.println(line.replaceFirst(".*?,", ""));
Regex explanation:
(\r?\n)? means an optional new-line character.
. means a wildcard.
.*? means 0 or more wildcards (*? as opposed to just * means non-greedy matching, but this probably doesn't mean much to you).
, means, well, ..., a comma.
Reference.
split for file or single string:
String line = "1.2223232323232323,74.00";
String value = line.split(",")[1];
split for one giant string (also needs regex) (but I'd prefer Scanner, it doesn't need all that memory):
String line = "1.22,74.00\n1.22,74.00\n1.22,74.00";
String[] array = line.split("(\r?\n)?.*?,");
for (int i = 1; i < array.length; i++) // the first element is empty
System.out.println(array[i]);
Just try with:
String[] parts = "1.2223232323232323,74.00".split(",");
String value = parts[1]; // your 74.00
String[] strings = "1.2223232323232323,74.00".split(",");