[java] operation on strings

Started by
3 comments, last by Jaykumar 14 years, 5 months ago
Hi i want to store two separate strings separated by a space in an array and then retrieve the strings using some indexing method and store them in a 2 dimensional array. in this code the dummy is a character array already populated with the 2 strings using the if condition I'm separating the strings from the dummy array. inside the if condition I'm trying to store the first string in the first row of the 2dim array and the second string in the second row. however when i try to print out the string in temp[row], its printing junk values. please help for(j=0;j<ln;j++) { dummy[j]=total.charAt(j); if(dummy[j]==' ') { temp[row][col]='\0'; System.out.println("word: " + temp[row]); row++; col=0; } else { temp[row][col]=total.charAt(j); col++; } }
Advertisement
temp[row] is a char[] type, the important part being that it is an array type. The toString() of an array type gives the address specifier (that 'junk' being printed). There is no special logic for char[] that converts it to a String automatically.
How about:
System.out.println( new String(temp[row]) );
Also, why not try something like?:

char[][] temp = new char[2][];String[] s = total.split(" ", temp.length);for(int i = 0; i < s.length; ++i)	temp = s.toCharArray();


Or, if you can't handle temp being a jagged array;

char[][] temp = new char[2][SOME_MAX_LEN];String[] s = total.split(" ", temp.length);for(int i = 0; i < s.length; ++i)	System.arraycopy(s.toCharArray(), 0, temp, 0, s.length());


.. remembering to handle the IndexOutOfBoundsException if a substring of the total string can't fit in a row of temp in this version.
Thanks a lot!It works :)

cheers
jay

This topic is closed to new replies.

Advertisement