Search code examples
javajspgetstring

Split the getString result into multiple values according to columns


<%
  st = con.createStatement();
  rs = st.executeQuery("select pf_nm from portfolio");

  while(rs.next())
  {
    out.print(rs.getString(1)); //divide the result into multiple values
  }
 %>

The result in above code may vary according to data fetched. Example of result is as below:

Google Facebook
or
Google
or 
Google Facebook Apple

Solution

  • If I understood your question and comment correctly then you can do something like this

    ArrayList<String> cols = new ArrayList<String>();
    while(rs.next())
      {
        cols.add(rs.getString(1));
        // Do something..
      }
    

    Edit : What I understood from your previous question

    String result = rs.getString(1); // gives "Google Facebook Apple AT&T" as result
    String[] names = result.split("\\s"); // Split the line by whitespace
    

    If you want you can also make use of ArrayList. You can also use hashMap if you required key values assoiciation (I am not sure thats what you want). Following are some useful links

    1. Splitting string in java

    2. How to use ArrayList in Java

    3. HashMap example in Java

    Here is complete pseudo code for you.

    public class StringSplit {
    
        public static void main(String [] sm){
            String str = "Google Facebook Apple AT&T";
            // If you have more than one whitespace then better use \\s+
            String[] names = str.split("\\s");
            for(int i =0; i<names.length; i++){
                System.out.println(i +" : " + names[i]);
            }
        }
    }
    

    I hope this helps you.