Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Is it possible to test the first few chars of a string

Options
  • 30-11-2005 3:04pm
    #1
    Registered Users Posts: 7,498 ✭✭✭


    Just windering if it is possible to test the first few chars of a string

    eg

    String a = "user john";

    If(first 4 chars is "user")
    System.out.println(print out "john");


    the above string is likely to be sent down from a class or something not sure yet.


Comments

  • Moderators, Education Moderators Posts: 1,863 Mod ✭✭✭✭Slaanesh


    if(a.startsWith("user "))
    System.out.println(a.substring(5,a.length()));

    Or thereabouts.


  • Registered Users Posts: 7,498 ✭✭✭BrokenArrows


    works like a charm thanks.


  • Registered Users Posts: 7,498 ✭✭✭BrokenArrows


    One more thing.


    If the string is passed down as "user John something"

    Can i print out Just john. ie print until a space is reached.


  • Moderators, Education Moderators Posts: 1,863 Mod ✭✭✭✭Slaanesh


    String a = "user john soimethingssdffs";
    
    	if(a.startsWith("user "))
    	{
    		if(a.lastIndexOf(" ") >5)
    		{
    			System.out.println(a.substring(5,a.lastIndexOf(" ")));
    		}
    		else
    		{
    			System.out.println(a.substring(5,a.length()));
    		}
    	}
    
    Note: If you have "user john something something"

    The result will be "john something"

    You could check up to the second space only if need be.


  • Registered Users Posts: 304 ✭✭PhantomBeaker


    http://java.sun.com/j2se/1.5.0/docs/api/java/util/StringTokenizer.html

    Just look at the example involving the .split() method in the String class - StringTokenizer is deprecated, so best not get into the habit of using it if they're going to pull it.


  • Advertisement
Advertisement