Splitproov.java

Allikas: Lambda
// Vaike demo kasurealt stringi lugemise ja parsimise kohta
//
// Olulist tahele panna:
//   - Programm loeb kasurealt yhe stringi, kus on eraldava stringiga eraldatud sonad
//   - loetakse kokku eraldajad ja trykitakse nende arv valja
//   - string lohutakse eraldaja jargi (vaikimisi koma, voib olla ka muu string)
//   - sona alguses ja lopus olevad tyhikud visatakse ara
//   - tehakse stringimassiiv ja sonad pannakse ykshaaval sinna massiivi
//   - lopuks trykitakse sonad massiivist valja


// Must import java.io.* in order to get access to libraries

import java.io.*;

public class splitproov {

  public static void main(String[] args) {
    
    String input;  
    String[] words;
    String separator=","; // NB! You can use any string as a separator!
    
    int i;
    int len;
    int count;
    int pos;
    int ws;
    int we;
    
    /* Get input from the command line.
       If the command line does not contain input,
       print an error message and end this program. */
    
    if (args.length == 1) {
      input = args[0];   
    }
    else {
      System.out.println("Usage:  java splitproov \"mingitekst\"");      
      return;
    }
    
    /* count the number of separators: 
       then we know the required size of the array */
    
    len=input.length();
    count=0;
    pos=-1;
    for(;;) { // loop over all occurrences of separator in input
      pos=input.indexOf(separator,pos+1);  // search from last pos found!
      if (pos<0) break; // none found after pos
      count++;  
    }  
      
    // let us print some useful debug information
    System.out.println("\nFound "+count+" separators "+separator);    
    
    // make a suitable array    
    words=new String[count+1];  
    
    // loop again over the input, this time collecting strings    
    ws=0;  // word start
    we=ws+1; // word end
    count=0;
    pos=-1;
    for(;;) { // again, loop over all occurrences of separator in input
      pos=input.indexOf(separator,pos+1);  // search from last pos found!
      if (pos<0) {
        // no separator found after pos: take to end of string
        we=input.length();
      } else {                
        // separator found
        we=pos;
      }  
      words[count]=input.substring(ws,we).trim(); // take substring, remove spaces          
      ws=pos+separator.length(); // this is where the next word will start
      count++;  
      if (pos<0) break;
    }  
    
    // print the contents of the array
    for(count=0;count<words.length;count++) {
      System.out.println("Word nr "+count+": "+words[count]);               
    }         
  } 
     
}