Question

i have a String output ( a paragraph ) having almost 140 lines , i want to search for a word in this paragraph and get its line in the paragraph for example i have :

date : 08/12/2009
value : 589.236
smth : smth 
Fax : 25896217

i search for the word value , it gives me the line 2 in the paragraph , actually i used this code to get the number of lines :

String resultat = "..."
Matcher m = Pattern.compile("(\n)|(\r)|(\r\n)").matcher(resultat);
    int lines = 1;
    while (m.find())
    {
        lines ++;
    }

is there a predefined method in java that gives me the line of the found word ?

Was it helpful?

Solution 2

As far as I know, there is none. So my solution would be to split text into lines and scan text line by line, until the word is found. Then return a line number.

public class LineNumber {
    public static void main(String[] args) {
        String text = "date : 08/12/2009" + "\n" + "value : 589.236" + "\n"
                + "smth : smth" + "\n" + "Fax : 25896217";

        System.out.println("'smth' first found at line: "
                + findFirstOccurenceLineNumber(text, "smth"));
    }

    private static int findFirstOccurenceLineNumber(String text, String needle) {
        String lines[] = text.split("\r|\n|\r\n|\n\r", -1);
        int lineNumber = 1;
        for (String line : lines) {
            if (line.contains(needle)) {
                return lineNumber;
            }
            lineNumber++;
        }
        return -1;
    }
}

OTHER TIPS

One solution would be to get lines by splitting the String value by line-end character and check each line for occurence of the searched value and return the linenumber on found event. A possible implementation could be:

private static int findPartInArray(String[] text, String needle) {
    int lineNumber = 0;
    for (String line : lines) {
        if (line.contains(needle)) {
            return lineNumber + 1;
        }
        lineNumber++;
    }
    return -1;
}

Example usage:

String input = "date : 08/12/2009" + "\n" + "value :  589.236" + "\n"
    + "smth : smth" + "\n" + "Fax : 25896217";
String[] lines = input.split("(\\n)|(\\r)|(\\r\\n)");
int res = findPartInArray(lines, "value");
if (res > 0)
System.out.println("not found");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top