DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

+ Reply to Thread
Results 1 to 4 of 4
  1. #1
    Join Date
    Feb 2005
    Posts
    24

    Question Isolate 2nd or 3rd instance of .indexOf(something)

    Coding Style: NetBeans IDE 4.0 Beta2 (Java)

    Given the following string
    String Info = "NAME:ME IP:192.168.0.1 PORT:4444"
    I wanted to extract the information from the string using .substring and .indexOf, specifically .Substring(.indexOf("NAME:")+5, .indexOf(" "));

    That works GREAT however accessing the rest won't (outofbounds errors): .subString(.indexOf("IP:")+3, .indexOf(" "))
    This fails (I think) because my .indexOf(" ") is returning the index of the 1st space (after NAME:ME) and not the next one after IP:192.168.0.1

    So how can I make .indexOf jump to the NEXT (" ") character? Or is there a better way to do this?
    Any help would be appreciated, Thanks,

  2. #2
    Join Date
    Aug 2004
    Location
    Dublin, Ireland
    Posts
    63
    Why don't you use a string tokenizer and just enumerate through the resultant collection?
    VBForums.com & DevX.com Super Moderator
    Microsoft MVP : Visual Developer - Visual Basic
    My Website

  3. #3
    Join Date
    Feb 2004
    Posts
    541
    StringTokenizer is deprecated. The API advises to use String.split() instead. You can see how to use the method here...http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#split(java.lang.String)

    I think you may be best splitting the string on the spaces as follows...

    Code:
    String[] stringArray = yourString.split(" ");
    stringArray will then be an array of String objects containing

    NAME:ME - index 0
    IP:192.168.0.1 - index 1
    PORT:4444 - index 2

  4. #4
    Join Date
    Aug 2004
    Location
    Dublin, Ireland
    Posts
    63
    Shows the last time I used Java
    Anyway, Split() has been in VB since VB6 and its excellent
    VBForums.com & DevX.com Super Moderator
    Microsoft MVP : Visual Developer - Visual Basic
    My Website

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


Top DevX Stories

Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL


Sponsored Links