开发者

how to find part of line java?

开发者 https://www.devze.com 2023-01-23 12:05 出处:网络
I need some portion of开发者_如何学Go the file to display.Actually by using Matcher and Pattern I found a word in the file .By using Matcher.start() and Matcher.end() I got the postion of the word.But

I need some portion of开发者_如何学Go the file to display.Actually by using Matcher and Pattern I found a word in the file .By using Matcher.start() and Matcher.end() I got the postion of the word.But how can i get the words before and after this word without splitting.This is like a home work program.Plz help me out.

For example:File.txt :

contains the above lines only.then in that I found "the" word at 23 and 26 postion.Now I want "some portion of" , "file to display." words.

Actually ,by using String.substring(start,end) we will get some part but I need exactly words.If i take substring it is giving, cutting part of the words.


String toFind = "day";
String sentence = "wolfrevokcatS no snoitseuq krowemoh tsop ot yad enif a si tI";

char[] charArray = sentence.toCharArray();

String reversedSentence = "";

for(int i = 0; i < charArray.length; ++i) {
    reversedSentence += charArray[charArray.length - i - 1];
}

System.out.println(reversedSentence);
boolean matches = reversedSentence.matches(".+" + toFind + ".+");

if(matches) {

    int start = reversedSentence.indexOf(toFind);
    int end = start + toFind.length();

    System.out.println("Before word to find: " + reversedSentence.substring(0, start));
    System.out.println("Word to find: " + reversedSentence.substring(start, end));
    System.out.println("After word to find: " + reversedSentence.substring(end, reversedSentence.length()));
}

Here is a solution that uses regular expressions. If you manage to understand this code, you'll do well with string manipulation in Java. I haven't proved it's correct for all inputs, I leave it as an exercise to the question's author.


The trick is to remember that the String.range method is really cheap in Java. So what you do is get the substrings that are the “string before the matched pattern” and the “string after the matched pattern” and apply suitable other regular expressions to extract the answers you want from those.

0

精彩评论

暂无评论...
验证码 换一张
取 消