StringTokenizer class

hello every one
i have been programming in C++ since 2005, but i am novice to JAVA world
i've coded a very simple exercise that asks to tokenize a string into tokens then sort them and finally print tokens each in line.
i wrote the following code
[code]
import java.util.StringTokenizer;
public class Ex3 {
public static void main(String[] args) {
String s = "Hello world, Hello C++, Hello Java all of these programs are your first programming projects";
StringTokenizer st = new StringTokenizer(s);
String[] sarr = new String[st.countTokens()];
for(int i=0; i 0) {
String tmp = sarr[i];
sarr[i] = sarr[j];
sarr[j] = tmp;
}
}
}
System.out.println(s);
for(int i=0; i<st.countTokens(); i++)
System.out.println(sarr[i]);
}
}
[/code]
expecting the following result:
C++, Hello, Hello, Hello, JAVA, all, are, first, of, programming, programs, projects, these, world, your.
but i got the following result:
C++, Hello, Hello, Hello, Java, all, world.
where is the rest ?

Comments

  • Hi luckyboy, StringTokenizer is deprecated. The following code is shorter and works better:

    [code]public static void main(String[] args) {
    String s = "Hello world, Hello C++, Hello Java all of these programs are your first programming projects";
    String[] tokens = s.split(",");

    for(int i=0; i<tokens.length; i++) {
    tokens[i] = tokens[i].trim();
    System.out.println(tokens[i]);
    }
    }[/code]
  • Sorry, I didn't see that you also needed to sort them. Just mix your original code with this code and you should be sorted (heh) :)
  • [code] String s = "Hello world, Hello C++, Hello Java all of these programs are your first programming projects";
    String[] tokens = s.split(",");
    for (int i = 0; i < tokens.length; i++) tokens[i] = tokens[i].trim();
    Arrays.sort(tokens);
    for(int i=0; i<tokens.length; i++) System.out.println(tokens[i]);[/code]
  • thanks a lot, but i didn't understand Why the error happened ?
    where is the rest?
  • The rest of the code wasn't needed. I'm using the default comparator object on strings (like the original code was doing) and automating the sort, but an external function in Arrays already provides this functionality for arrays of object. I'm not sure why the StringTokenizer problem happened either, but we have to assume that the underlying semantics and usage must be different...
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories