1

Let's say I have a continuous String name as temp. The string is divided by new lines, How can I use StringTokenizer on it and get each line separately?

String temp = "I

am

a 

college

kid";

Thank You

Kaustubh Khare
  • 3,280
  • 2
  • 32
  • 48
  • From the [JavaDocs](https://docs.oracle.com/javase/8/docs/api/java/util/StringTokenizer.html) *"StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead."*, although, I might also recommend using `Scanner` – MadProgrammer Mar 23 '18 at 04:39
  • For many basic questions like this, your first course of action should be to Google the question and see if there are any relevant answers. – markspace Mar 23 '18 at 04:46
  • yeah, from now I will. thanks –  Mar 23 '18 at 04:50

2 Answers2

3
StringTokenizer st = new StringTokenizer(temp,"\n");  
     while (st.hasMoreTokens()) {  
     System.out.println(st.nextToken());  
     }  

Will do the job. However try to use split method of string class like

String lines[] = string.split("\\r?\\n");
Manvi
  • 1,136
  • 2
  • 18
  • 41
1
StringTokenizer st = new StringTokenizer(temp,System.lineSeparator());
     while (st.hasMoreTokens()) {
         println(st.nextToken());
     }
eddytnk
  • 96
  • 1
  • 9
  • Should be careful with `System.lineSeparator()` here. If the string didn't come from some native source on the system, it may well have a different separator. For example, HTTP line breaks are always `\r\n`, not what the local system defines. – markspace Mar 23 '18 at 04:43
  • @markspace Hey! thanks for helping me out, this works in my code but I need to check what System.lineSeparator() is. –  Mar 23 '18 at 04:48