Jump to Real's How-to Main page

Convert a String to an array

NOTE: This HowTo was designed for JDK 1.0.2. Starting with version 1.4, the String class offers a better way to split a String into an Array. It's the String.split(regexp) method. See this HowTo.

Thanks to T. GUIRADO

public String[] stringtoArray( String s, String sep ) {
  // convert a String s to an Array, the elements
  // are delimited by sep
  StringBuffer buf = new StringBuffer(s);
  int arraysize = 1;
  for ( int i = 0; i < buf.length(); i++ ) {
    if ( sep.indexOf(buf.charAt(i) ) != -1 )
      arraysize++;
  }
  String [] elements  = new String [arraysize];
  int y,z = 0;
  if ( buf.toString().indexOf(sep) != -1 ) {
    while (  buf.length() > 0 ) {
      if ( buf.toString().indexOf(sep) != -1 ) {
        y =  buf.toString().indexOf(sep);
        if ( y != buf.toString().lastIndexOf(sep) ) {
          elements[z] = buf.toString().substring(0, y ); 
          z++;
          buf.delete(0, y + 1);
        }
        else if ( buf.toString().lastIndexOf(sep) == y ) {
          elements[z] = buf.toString().substring
            (0, buf.toString().indexOf(sep));
          z++;
          buf.delete(0, buf.toString().indexOf(sep) + 1);
          elements[z] = buf.toString();z++;
          buf.delete(0, buf.length() );
        }
      }
    }
  }
  else {
    elements[0] = buf.toString(); 
  }
  buf = null;
  return elements;
}

To transform back to String

public String arrayToString(String s[], String sep) {
  int k;
  String result = "";

  k = s.length;
  if (k > 0) {
     result = s[0];
     for (int i= 1 ; i < k; i++) {
       result += sep + s[i] ;
     }
  }
  return result;
}

If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2005
[ home ]