Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 16 of 16

Thread: Seperating Strings

  1. #1
    Member
    Join Date
    Jun 2011
    Posts
    94
    My Mood
    Amazed
    Thanks
    22
    Thanked 1 Time in 1 Post

    Default Seperating Strings

    Hi,
    I was trying to learn about dealing with Strings. I came across with StringTokenizer. It seemed like it makes things easier, but I cannot seperate a text if I put a space between words. Here is my code for it:
    public class Tokening {
    String str;
    Scanner input;
    StringTokenizer token;
     
           public void methodOne(){
     
    		input = new Scanner(System.in);
    		System.out.println("Enter some text here:");
    		str = input.next();
    		token = new StringTokenizer(str,":;.,  "); 
    		int tokenCount = token.countTokens();
    		System.out.println(tokenCount);
    		while(token.hasMoreTokens()){
    		String z = token.nextToken();
    		System.out.println(z);
    		}
     
    	}
     
    }
    When I try this, I put "Here we go, trying to use String,Tokenizer. Hope the best!", it only shows "Here" as the output. That's why I included lines to count the tokens. And it seems I only have 1 tokenizer here.

    Looking deeper into seperating strings, I found out that there is a String method called "split". But this didn't help too. I was trying to use more than one delimiters. It failed. I was convinced one would enough, but it produced the same output as StringTokenizer. Here is the code for this - In the same class, so the variables are the same:
    public void metotIki(){
    		input = new Scanner(System.in);
    		System.out.println("Enter some text here:");
    		str = input.next();
    		String[] stg = str.split(",");
    		for(int x=0;x<stg.length;x++){
    			System.out.println(stg[x]);
    		}

    So, I want to seperate text when the user puts a comma, a period and the other signs like ; : ? and I want to do it whether there are whitespaces between the words. How can I do that?
    Last edited by beer-in-box; September 14th, 2011 at 11:59 AM. Reason: Deleted a comment line which was not in English :)


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,607
    My Mood
    Hungover
    Thanks
    145
    Thanked 658 Times in 563 Posts

    Default Re: Seperating Strings

    From the StringTokenizer API:

    "StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead."

    Stick with String.split(), and give the Pattern API a read-through for regular expression help.

    Pattern (Java Platform SE 6)
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    Member
    Join Date
    Jun 2011
    Posts
    94
    My Mood
    Amazed
    Thanks
    22
    Thanked 1 Time in 1 Post

    Default Re: Seperating Strings

    Thanks for the answer. I also learnt that StringTokenizer is a legacy class while I was researching about splitting text.

    About the Pattern API, either I miss something big or it won't help me either. And also I don't think I am using it as it should be used. Here is my new code and comments about what I think I am doing.

    public void methodThree(){
    		input = new Scanner(System.in);
    		System.out.println("Enter some text here:");
    		str = input.next();
    		Pattern deneme = Pattern.compile(str); //Compiling my string into a Pattern
    		String[] stg = deneme.split(":"); //Splitting my pattern into an array whenever colon is used
     
    		for(int x=0;x<stg.length;x++){
    			System.out.println(stg[x]); //Printing the new array out.
    		}
    		}

    In the "Method Detail", I only found split methods to be used for my purpose. However, I think I am doing it wrong, because it seems there is no difference between using String.split() or Pattern.split().
    But, the funny thing which made me think I am doing it wrong is that the output of this code is a colon (. And the user input doesn't matter.

  4. #4
    Member
    Join Date
    Jun 2011
    Posts
    94
    My Mood
    Amazed
    Thanks
    22
    Thanked 1 Time in 1 Post

    Default Re: Seperating Strings

    Haha, I should have read more carefully. Ignore the previous post please
    I found the answer to my first question:
    public void metotUc(){
    		input = new Scanner(System.in);
    		System.out.println("Enter some text here:");
    		str = input.next();
    		Pattern pat = Pattern.compile(":");
     
    		String[] stg1 = pat.split(str);
     
    		for(int x=0;x<stg1.length;x++){
    			System.out.println(stg1[x]);
    		}
    		}

    But what happens when I want to use both : and ; as delimiters? And I can't still seperate the words if I enter "Yes : we are here" instead of "Yes:we are here."

    EDIT: OK, I tried it all, I used " ", " : ", ": " and " :" as parameters to String.split() and Pattern.compile() and it didn't worked. So, if my text includes a space (or maybe other whitespaces too), I cannot split it.
    Last edited by beer-in-box; September 14th, 2011 at 01:07 PM.

  5. #5
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,607
    My Mood
    Hungover
    Thanks
    145
    Thanked 658 Times in 563 Posts

    Default Re: Seperating Strings

    Can't you just use something like "[;: ]"?
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  6. The Following User Says Thank You to KevinWorkman For This Useful Post:

    beer-in-box (September 14th, 2011)

  7. #6
    Member
    Join Date
    Jun 2011
    Posts
    94
    My Mood
    Amazed
    Thanks
    22
    Thanked 1 Time in 1 Post

    Default Re: Seperating Strings

    Thank you once again. This solves one of my problems here.
    But I still have the same damn thing. Why do I have "This" as an output when I enter "This is a trial, to use split: methods."? How can I make Java go on the text after a space?
    All my codes worked when there are no spaces. Including Pattern class and your last suggestion to use "[.,:]", all my codes failed when the input includes a space. They can work before the space. But not after the space.

    I cannot depend on the possibility of user input's having no spaces. So, there should be a method or a technique to overcome this.

  8. #7
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,607
    My Mood
    Hungover
    Thanks
    145
    Thanked 658 Times in 563 Posts

    Default Re: Seperating Strings

    I'm not really sure what you mean. Would you mind throwing together an SSCCE that shows what you're talking about, with the output you expect vs what you're getting?
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  9. #8
    Member
    Join Date
    Jun 2011
    Posts
    94
    My Mood
    Amazed
    Thanks
    22
    Thanked 1 Time in 1 Post

    Default Re: Seperating Strings

    I suspected this So, I will examplify it. Here is my code again, which works when the input doesn't have a space:
    public void metotUc(){
    		input = new Scanner(System.in);
    		System.out.println("Enter some text here:");
    		str = input.next();
    		Pattern pat = Pattern.compile("[.,:;! ]");
     
    		String[] stg1 = pat.split(str);
     
    		for(int x=0;x<stg1.length;x++){
    			System.out.println(stg1[x]);
    		}
    		}

    My input to the program: "This will be that: a great, colorful, peaceful world: WTF!"
    What I expect:
    "This
    will
    be
    that
    a
    great
    ... and so on.
    What I get: "This"

    I hope that helps you to understand what I mean. I am sorry for not being able to explain my problem better and more clear

  10. #9
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,607
    My Mood
    Hungover
    Thanks
    145
    Thanked 658 Times in 563 Posts

    Default Re: Seperating Strings

    That's not really what I meant. You're making this harder than it should be. Try this out:

        public static void main(String... args){
        	String str = "This will be that: a great, colorful, peaceful world: WTF!";
     
        	String[] pieces = str.split("[:,\\s]+");
     
        	for(String s : pieces){
        		System.out.println(s);
        	}
        }
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  11. The Following User Says Thank You to KevinWorkman For This Useful Post:

    beer-in-box (September 14th, 2011)

  12. #10
    Member
    Join Date
    Jun 2011
    Posts
    94
    My Mood
    Amazed
    Thanks
    22
    Thanked 1 Time in 1 Post

    Default Re: Seperating Strings

    It works when I use it like you use (when I define the string and don't get from the user). But when I want to use it with Scanner, it fails. Could you run this code when you are free and tell me why it doesn't work as it should be?

    public static void main(String[] args) {
     
    	  	Scanner input = new Scanner(System.in);     //This three lines
    		System.out.println("Enter some text here:");  //are the only codes
    		String str = input.next();                            //which are different than yours.
     
    	    	String[] pieces = str.split("[:,\\s]+");
     
    	    	for(String s : pieces){
    	    		System.out.println(s);
    	    	}
    	}

    So, why does this happen all the time when I want to get input from the user?

  13. #11
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,607
    My Mood
    Hungover
    Thanks
    145
    Thanked 658 Times in 563 Posts

    Default Re: Seperating Strings

    Ohhhh I see.

    Scanner.next() gives you the next token, based on a customizable delimiter pattern.
    To do it my way, you'd want Scanner.nextLine() instead.

    But you could avoid all the String.split stuff if you just used the delimiter pattern in the Scanner in the first place and let it separate them out for you.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  14. The Following User Says Thank You to KevinWorkman For This Useful Post:

    beer-in-box (September 14th, 2011)

  15. #12
    Member
    Join Date
    Jun 2011
    Posts
    94
    My Mood
    Amazed
    Thanks
    22
    Thanked 1 Time in 1 Post

    Default Re: Seperating Strings

    Okay, so all happened because I was lazy and didn't use nextLine...

    So, can you examplify what you told please?

    And,in "[:,\\s]+", why are we using "+" and why do we put two "\"s?

  16. #13
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,607
    My Mood
    Hungover
    Thanks
    145
    Thanked 658 Times in 563 Posts

    Default Re: Seperating Strings

    Quote Originally Posted by beer-in-box View Post
    Okay, so all happened because I was lazy and didn't use nextLine...
    More or less, yeah.

    Quote Originally Posted by beer-in-box View Post
    So, can you examplify what you told please?
    I'm not sure what you mean. What didn't you understand?

    Quote Originally Posted by beer-in-box View Post
    And,in "[:,\\s]+", why are we using "+" and why do we put two "\"s?
    Check out the pattern class to see what they are. Write a small program to play with them to see what they do.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  17. #14
    Member
    Join Date
    Jun 2011
    Posts
    94
    My Mood
    Amazed
    Thanks
    22
    Thanked 1 Time in 1 Post

    Default Re: Seperating Strings

    Quote Originally Posted by KevinWorkman View Post
    I'm not sure what you mean. What didn't you understand?
    This :

    Quote Originally Posted by KevinWorkman View Post
    But you could avoid all the String.split stuff if you just used the delimiter pattern in the Scanner in the first place and let it separate them out for you.
    Can you give me some clues so that I can try to figure it out. My first attempt failed as always

  18. #15
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,607
    My Mood
    Hungover
    Thanks
    145
    Thanked 658 Times in 563 Posts

    Default Re: Seperating Strings

    Quote Originally Posted by beer-in-box View Post
    This :
    Can you give me some clues so that I can try to figure it out. My first attempt failed as always
    What I meant was to use the Scanner.next() function, but specify the pattern delimiter like you are with the String.split() method. Check out the description at the top of the Scanner API to see how to do that.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  19. The Following User Says Thank You to KevinWorkman For This Useful Post:

    beer-in-box (September 14th, 2011)

  20. #16
    Member
    Join Date
    Jun 2011
    Posts
    94
    My Mood
    Amazed
    Thanks
    22
    Thanked 1 Time in 1 Post

    Default Re: Seperating Strings

    Thank you for the all knowledge you shared with me
    It was like a private lesson covering String topic!

Similar Threads

  1. Strings and Characters
    By av8 in forum What's Wrong With My Code?
    Replies: 12
    Last Post: July 3rd, 2011, 04:21 PM
  2. Question regarding Strings
    By yeeesh in forum Java Theory & Questions
    Replies: 2
    Last Post: November 30th, 2010, 12:09 PM
  3. Strings
    By Leeds_Champion in forum Algorithms & Recursion
    Replies: 3
    Last Post: November 3rd, 2009, 10:09 PM
  4. Strings
    By BeSwift21 in forum Java Theory & Questions
    Replies: 1
    Last Post: October 13th, 2009, 08:02 PM
  5. Replies: 2
    Last Post: June 19th, 2008, 04:58 AM