new KlotnetDeveloperCornerSnippet(Java);
CSV String to Vector Function

 1   public static Vector Csv2Vector(String src, String delimiter) {
 2 	if ( src==null ) return null;
 3 
 4 	int commaCount = 0;
 5 	int fieldStart = 0;
 6 	int bookmark = 0;
 7 	boolean openQuote = false;
 8 	Vector retEmpty = new Vector();
 9 
10 	for ( int count=0; count < src.length(); count++ ) {
11 	  if ( String.valueOf(src.charAt(count)).equals("\"") ) {
12 		if ( openQuote ) {
13 		  openQuote=false;
14 		} else {
15 		  openQuote=true;
16 		}
17 	  }
18 	  if ( String.valueOf(src.charAt(count)).equals(delimiter) ) {
19 		// if comma is found inbetween quote blocks
20 		if ( !(openQuote) ) {
21 		  commaCount++;
22 		}
23 	  }
24 	}
25 
26 	if ( commaCount==0 ) return retEmpty;
27 
28 	Vector ret = new Vector();
29 
30 	for ( int count=0; count < src.length(); count++ ) {
31 		if ( String.valueOf(src.charAt(count)).equals("\"") ) {
32 		  if ( openQuote ) {
33 			openQuote=false;
34 
35 		  } else {
36 			openQuote=true;
37 		  }
38 		}
39 		if ( String.valueOf(src.charAt(count)).equals(delimiter) ) {
40 		  // if comma is found inbetween quote blocks
41 		  if ( !(openQuote) ) {
42 			ret.addElement(stripQuotes(src.substring(fieldStart, count))+"");
43 
44 			fieldStart = count + 1;
45 			bookmark++;
46 			if ( bookmark == commaCount ) {
47 			  // getting the last column here
48 			  ret.addElement(stripQuotes(src.substring(fieldStart))+"");
49 			} // if bookmark == commacount
50 		  } // if not openQuote
51 		} // if current char == delimiter
52 	} //next
53 
54 	
55 	return ret;
56   }

 Klotnet Quick Links
© Copyright 2005 Klotnet Software LLC. All rights reserved.