Java: calculate linenumber from charwise position according to the number of "\n"
Posted
by HH
on Stack Overflow
See other posts from Stack Overflow
or by HH
Published on 2010-04-22T12:13:21Z
Indexed on
2010/04/22
13:53 UTC
Read the original article
Hit count: 230
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);
}
}
}
© Stack Overflow or respective owner