Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

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

  • 30-11-2005 03:04PM
    #1
    Registered Users, Registered Users 2 Posts: 7,546 ✭✭✭


    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,699 Mod ✭✭✭✭Slaanesh


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

    Or thereabouts.


  • Registered Users, Registered Users 2 Posts: 7,546 ✭✭✭BrokenArrows


    works like a charm thanks.


  • Registered Users, Registered Users 2 Posts: 7,546 ✭✭✭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,699 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, Registered Users 2 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