Android - how to delete last 2 lines from String? - java

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

Related

In Java is there any method to read a data of a line from file?

Is there a method to read the first and the last data from a line which are separated by space from a file in java.
Example:
the file contains the following information
100 20-11-2020 08:25:42 IN
101 21-09-2020 09:01:20 IN
Here I just want 100 and IN to extract and print
One approach is to read the entire string and use the split method. Store the split string in an array and simply access the first and last element., something like this:
String line = "100 20-11-2020 08:25:42 IN"
String arr[] = line.split(" ");
String var1 = arr[0];//stores 100
String var2 = arr[arr.length - 1];//stores IN
Hope that helps! Happy coding!

parsing values from text file in java

I've got some text files I need to extract data from. The file itself contains around a hundred lines and the interesting part for me is:
AA====== test==== ====================================================/
AA normal low max max2 max3 /
AD .45000E+01 .22490E+01 .77550E+01 .90000E+01 .47330E+00 /
Say I need to extract the double values under "normal", "low" and "max". Is there any efficient and not-too-error-prone solution other than regexing the hell out of the text file?
If you really want to avoid regexes, and assuming you'll always have this same basic format, you could do something like:
HashMap<String, Double> map = new HashMap<>();
Scanner scan = new Scanner(filePath); //or your preferred input mechanism
assert (scan.nextLine().startsWith("AA====:); //remove the top line, ensure it is the top line
while (scan.hasNextLine()){
String[] headings = scan.nextLine().split("\\s+"); //("\t") can be used if you're sure the delimiters will always be tabs
String[] vals = scan.nextLine().split("\\s+");
assert headings[0].equals("AA"); //ensure
assert vals[0].equals("AD");
for (int i = 1; i< headings.length; i++){ //start with 1
map.put(headings[i], Double.parseDouble(vals[i]);
}
}
//to make sure a certain value is contained in the map:
assert map.containsKey("normal");
//use it:
double normalValue = map.get("normal");
}
Code is untested as I don't have access to an IDE at the moment. Also, I obviously don't know what's variable and what will remain constant here (read: the "AD", "AA", etc.), but hopefully you get the gist and can modify as needed.
If each line will always have this exact form you can use String.split()
String line; // Fill with one line from the file
String[] cols = line.split(".")
String normal = "."+cols[0]
String low = "."+cols[1]
String max = "."+cols[2]
If you know what index each value will start, you can just do substrings of the row. (The split method technically does a regex).
i.e.
String normal = line.substring(x, y).trim();
String low = line.substring(z, w).trim();
etc.

What am I not seeing whilst getting info from a String[]

I am trying to split up my info first into a String[] by using "\n" as delimiter and than afterwards ,split them again into a String[] but this time using ";" as delimiter.
I however fail at getting info out of the second split.
public static void initHashMap(){
String[] lijnen = readDefinitioncsv(definitioncsv).split("\n");
for (int i =2;i<lijnen.length;i++){
String[] detaillijn = lijnen[i].split(";");
// on the line below I get
//java.lang.ArrayIndexOutOfBoundsException: 1
int rood = Integer.parseInt(detaillijn[1]);
int groen = Integer.parseInt(detaillijn[2]);
int blauw = Integer.parseInt(detaillijn[3]);
String provincieNaam = detaillijn[4];
RGBProvince.put(new Color(rood,groen,blauw), provincieNaam);
}
}
Thank you for your time
String[] lijnen = readDefinitioncsv(definitioncsv).split("\r?\n");
for (int i =2;i<lijnen.length;i++){
String[] detaillijn = lijnen[i].split("[,;\t]");
if (detaillijn.length < 5) {
throw new IllegalArgumentException("Weiniger als 5 elementen: "
+ lijnen[i]);
}
This handles Windows line endings (\r\n aka CR+LF) and also other forms of CSV - as ; did not seem to function.
May the file ends with an empty line, in which case you need to skip that with a continue.
For good order, indices start at 0; you seem to be skipping 2 header lines, and the first column.
Why is your for loop initializing at the third position?
for (int i =2;i<lijnen.length;i++){
presumably you want i=0?
also you array might not have 2 elements:
int rood = Integer.parseInt(detaillijn[1]);
this is the second position. but it might have nothing because of the loop above.
You should probably check you have at least those many lines / columns before you hop straight to one in an array.
You're initializing i to 2 in your for loop. If your array has less than three items, you will get an index out of bounds trying to access a location that does not exist.
Why not start with int i = 0?

Java: How To Grab Each nth Lines From a String

I'm wondering how I could grab each nth lines from a String, say each 100, with the lines in the String being seperated with a '\n'.
This is probably a simple thing to do but I really can't think of how to do it, so does anybody have a solution?
Thanks much,
Alex.
UPDATE:
Sorry I didn't explain my question very well.
Basically, imagine there's a 350 line file. I want to grab the start and end of each 100 line chunk. Pretending each line is 10 characters long, I'd finish with a 2 seperate arrays (containing start and end indexes) like this:
(Lines 0-100) 0-1000
(Lines 100-200) 1000-2000
(Lines 200-300) 2000-3000
(Lines 300-350) 3000-3500
So then if I wanted to mess around with say the second set of 100 lines (100-200) I have the regions for them.
You can split the string into an array using split() and then just get the indexes you want, like so:
String[] strings = myString.split("\n");
int nth = 100;
for(int i = nth; i < strings.length; i + nth) {
System.out.println(strings[i]);
}
String newLine = System.getProperty("line.separator");
String lines[] = text.split(newLine);
Where text is string with your whole text.
Now to get nth line, do e.g.:
System.out.println(lines[nth - 1]); // Minus one, because arrays in Java are zero-indexed
One approach is to create a StringReader from the string, wrap it in a BufferedReader and use that to read lines. Alternatively, you could just split on \n to get the lines, of course...
String[] allLines = text.split("\n");
List<String> selectedLines = new ArrayList<String>();
for (int i = 0; i < allLines.length; i += 100)
{
selectedLines.add(allLines[i]);
}
This is simpler code than using a BufferedReader, but it does mean having the complete split string in memory (as well as the original, at least temporarily, of course). It's also less flexible in terms of being adapted to reading lines from other sources such as a file. But if it's all you need, it's pretty straightforward :)
EDIT: If the start indexes are needed too, it becomes slightly more complicated... but not too bad. You probably want to encapsulate the "start and line" in a single class, but for the sake of brevity:
String[] allLines = text.split("\n");
List<String> selectedLines = new ArrayList<String>();
List<Integer> selectedIndexes = new ArrayList<Integer>();
int index = 0;
for (int i = 0; i < allLines.length; i++)
{
if (i % 100 == 0)
{
selectedLines.add(allLines[i]);
selectedIndexes.add(index);
}
index += allLines[i].length + 1; // Add 1 for the trailing "\n"
}
Of course given the start index and the line, you can get the end index just by adding the line length :)

Java loop to collect the second and third elements every three in an array

I have a file with data in the form timestamp, coordinate, coordinate, seperated by spaces, as here;
14:25:01.215 370.0 333.0
I need to loop through and add the coordinates only to an array. The data from the file is read in and put into as String[] called info, from split(" "). I have two problems, I think the end of the file has a extra " " which I need to lose appropriately and I also want confirmation/suggestions of my loop, at the moment I am getting sporadic out of bounds exceptions. My loop is as follows;
String[] info;
info = dataHolder.split(" ");
ArrayList<String> coOrds1 = new ArrayList<String>();
for (int counter = 0; counter < info.length; counter = counter+3)
{
coOrds1.add(info[counter+1]);
coOrds1.add(info[counter+2]);
}
Help and suggestions appreciated.
The text file is here but the class receives in a UDP packet from another class so I am unsure if this potentially adds " " at the end or not.
There are various classes/methods in Google's Guava library that could help with this task, in particular Splitter.omitEmptyStrings() which will discard any trailing space at the end of the file:
String input = Files.toString(file, Charsets.US_ASCII);
Iterable<String> fields =
Splitter.on(" ")
.omitEmptyStrings()
.split(input);
List<Coord> coords = Lists.newArrayList();
for (List<String> group: Iterables.partition(fields, 3)) {
String t = group.get(0);
double x = Double.parseDouble(group.get(1));
double y = Double.parseDouble(group.get(2));
coords.add(new Coord(t, x, y));
}
The problem will occur if you have an extra space at the end, because you are testing for counter < info.length and using counter + 1 and counter + 2. Try changing the loop conditions to:
for (int counter = 0; counter + 2 < info.length; counter = counter+3)
There is no need for external libraries.
You could just call dataHolder.trim(); which will remove any whitespace from the beginning and end your string. Then using dataHolder.split("\s"); //splits on "whitespace", you will receive an array consisting only of your data and with the appropriate size.
This will save you all the checks at each iteration whether counter+2 is still within the scope of the array. While still a valid solution, this could introduce further problems in the future due to its inherent nature of being "check-to-validate" - you simply might forget to process one of the cases - while trimming the string beforehand makes it structurally, constructed valid and there is no need to process special cases.

Categories