简体   繁体   中英

How to number certain text on java?

I'm trying to create a program that outputs certain keywords and what line they are on. I want the output to resemble something like:

1, Keyword, Public

1 is supposed to be the line that the word is on but i cannot figure out how to do this for each subsequent line.

You can maintain a counter for the line number as you go along starting from 1 and increment it every time you hit the newline char in the text. Or,

boolean hasNewLine(String str) {
  Pattern regex = Pattern.compile("^(.*)$", Pattern.MULTILINE);
  return regex.split(str).length > 0;
}

This will split the string in n parts, depending on the number of newline characters.

Or, If you're reading from a file, you can use this to count lines

BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
int lines = 0;
while (reader.readLine() != null) lines++;
reader.close();

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM