Java: calculate linenumber from charwise position according to the number of "\n"
- by HH
I know charwise positions of matches like 1 3 7 8. I need to know their corresponding line number.
Example: file.txt
Match: X
Mathes: 1 3 7 8.
Want: 1 2 4 4
$ cat file.txt
X2
X
4
56XX
[Added: does not notice many linewise matches, there is probably easier way to do it with stacks]
$ java testt
1
2
4
$ cat testt.java
import java.io.*;
import java.util.*;
public class testt {
public static String data ="X2\nX\n4\n56XX";
public static String[] ar = data.split("\n");
public static void main(String[] args){
HashSet<Integer> hs = new HashSet<Integer>();
Integer numb = 1;
for(String s : ar){
if(s.contains("X")){
hs.add(numb);
numb++;
}else{
numb++;
}
}
for (Integer i : hs){
System.out.println(i);
}
}
}