I'm trying to parse a String from a file that looks something like this:
Mark Henry, Tiger Woods, James the Golfer, Bob,
3, 4, 5, 1,
1, 2, 3, 5,
6, 2, 1, 4,
For ease of use, I'd like to split off the first line of the String, because it will be the only one that cannot be converted into integer values (the rest will be stored in a double array of integers[line][value]);
I tried to use String.split("\\\n") to divide out each line into its own String, which works. However, I am unable to divide the new strings into substrings with String.split("\\,"). I am not sure what is going on:
String[] firstsplit = fileOne.split("\\\n");
System.out.println("file split into " + firstsplit.length + " parts");
for (int i = 0; i < firstsplit.length; i++){
System.out.println(firstsplit[i]); // prints values to verify it works
}
String firstLine = firstsplit[0];
String[] secondSplit = firstLine.split("\\,");
System.out.println(secondSplit[0]); // prints nothing for some reason
I've tried a variety of different things with this, and nothing seems to work (copying over to a new String is an attempt to get it to work even). Any suggestions?
EDIT: I have changed it to String.split(",") and also tried String.split(", ") but I still get nothing to print afterwards.
It occurs to me now that maybe the first location is a blank one....after testing I found this to be true and everything works for firstsplit[1];
You're trying to split \\,, which translates to the actual value \,. You want to escape only ,.
Comma , doesn't need \ before it as it isn't a special character. Try using , instead of \\,, which is translated to \, (not only a comma, also a backslash).
Not only do you not need to escape a comma, but you also don't need three backslashes for the newline character:
String[] firstSplit = fileOne.split("\n");
That will work just fine. I tested your code with the string you specified, and it actually worked just fine, and it also worked just fine splitting without the extraneous escapes...
Have you actually tested it with the String data you provided in the question, or perhaps is the actual data something else. I was worried about the carriage return (\r\n in e.g. Windows files), but that didn't matter in my test, either. If you can scrub the String data you're actually parsing, and provide a sample output of the original String (fileOne), that would help significantly.
You could just load the file into a list of lines:
fin = new FileInputStream(filename);
bin = new BufferedReader(new InputStreamReader(fin));
String line = null;
List<String> lines = new ArrayList<>();
while (( line = bin.readLine()) != null ) {
lines.add( line );
}
fin.close();
Of course you have to include this stuff into some try catch block which fits into your exception handling. Then parse the lines starting with the second one like this:
for ( int i = 1; i < lines.size(); i++ ) {
String[] values = lines.get( i ).split( "," );
}
Related
I read a html file parser. Jsoup.parse(new File("2005-08.html"), "ISO-8859-1"); and then I need to split a string like "+24 -2" into two: "+24" and "-2". Then I pass this string to System.out.println() it prints as whitespase. I tried
s.split(" ");
s.split(" ");
but nothing works. I get one string "+24 -2".
You say your input is +24 -2 and you want to split it into +24 and -2.
Well that is pretty easy and it uses the same technique than your tried with:
String s = "+24 -2";
// The correct delimiter begins with an '&'
String[] result = s.split(" ");
// Print the result
System.out.println(Arrays.toString(result));
The output is [+24, -2]. You can access the results by result[0] which yields +24 and result[1] which is -2.
If you like you can also parse them as Integer by using:
int firstValue = Integer.parseInt(result[0]);
int secondValue = Integer.parseInt(result[1]);
I am trying to store the following strings in a file into a two dimensional array. What code I have written works except for when an element contains a space, it separates into an additional element. Here is my file:
Student1 New York
Student 2 Miami
Student3 Chicago
So I would want my output to look like this:
[Student1] [New York]
[Student 2] [Miami]
[Student3] [Chicago]
This is my actual output:
[Student1] [New] [York]
[Student] [2] [Miami]
[Student3] [Chicago]
Here is what I've written so far:
String file= "file.txt";
BufferedReader br = new BufferedReader(new FileReader(file));
while ((file = br.readLine()) != null) {
if (!file.isEmpty()) {
String strSingleSpace = file.trim().replaceAll("\\s+", " ");
String[] obj = strSingleSpace.trim().split("\\s+");
int i=0;
String[][] newString = new String[obj.length][];
for(String temp : obj){
newString[i++]=temp.trim().split("\\s+");
}
List<String[]> yourList = Arrays.asList(newString);
System.out.println(yourList.get(0)[0] + " " + yourList.get(1)[0]);
Just giving you some "food for thought": your code is treating all lines the same way. As if they were looking exactly the same. Although you already made it very clear, that some lines have a different format.
In other words: there is no point in blindly splitting on spaces, if sometimes spaces belong into the first or the second column.
Instead:
Determine the last index of a number in a line - and then everything up to that index "makes up the first column".
The remainder of that line (after that last number) should go into the second column; only call trim() on that remaining string to get rid of the potentially leading spaces.
You could put all of that into a single matching regular expression too; but as that is probably some kind of homework; I leave that exercise to the reader.
I think for your specific test case it will work if you change this line:
String[] obj = strSingleSpace.trim().split("\\s+");\
to this:
String[] obj = strSingleSpace.trim().split("\\s+", 1);
I have this code
String speed_string = "baka baka saka laka";
String[] string_array = speed_string.split(" ");
System.out.println(string_array.length);
and it returns the value of 1 when I run it. Why is that? It seems as if only the first word of the string gets saved.
Use \\s and update the code as below
String speed_string = "baka baka saka laka";
String[] string_array = speed_string.split("\\s");
System.out.println(string_array.length);
Most probably what you think is space (ASCII decimal 32) is not (in your input string).
That would explain perfectly the behavior you're seeing.
I have a String which always looks like this:
data
data
data
data
non-data
non-data
And I need to delete the 2 last lines from it. The lenght of these lines can be different. How I can do that fast (String = ~1000 lines)?
I'd say something along the lines of:
String[] lines = input.split("\n");
String[] dataLines = Arrays.copyOfRange(lines, 0, lines.length - 2);
int lastNewLineAt = string.lastIndexOf("\n");
string.subString(0, string.lastIndexOf("\n", lastNewLineAt));
You can use constant for new line character reading system property
This Code will split your text by "\n" 's which means your lines in to a String Array.
Than you will get that array's length..
And in a for loop you will set and append your text till your length-1 element.
This may be a long approach but I was searching this and I couldn't find anything.
This was my easiest way.
String[] lines = YourTextViev.getText().toString().split("\n");
YourTextView.setText(""); // clear your TextView
int Arraylength = lines.length-1; // Changing "-1" will change which lines will be deleted
for(int i=0;i<Arraylength;i++){
YourTextView.append(lines[i]+"\n");
}
Every time I try to split a string e.g. foo,bar,foo bar,bar it skips the string after the space.
How do I stop Java from doing this?
String[] transactionItem = transactionItems[i].split(",");
if transactioItems[0] = Y685,Blue Tie,2,34.79,2
it would output
transactionItem[0] = Y685
transactionItem[1] = Blue
transactionItem[3] = out of bounds
This code is working correctly:
String[] split = myString.split(",");
Basic demo : http://www.ideone.com/kLchx
With your new example, it works too : http://www.ideone.com/hWWzd
I think we need more code to search the problem.
This:
transactionItem[3]
Should be 2 instead of 3. Arrays are 0 indexed.