Isolate/remove parts of a String


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2

Thread: Isolate/remove parts of a String

  1. #1
    Join Date
    Feb 2005
    Posts
    24

    Question Isolate/remove parts of a String

    Coding Style: NetBeans IDE 4.0 Beta2 (Java)

    I need to find a good way to remove and isolate a part of a string, for example find the string below:
    String = "0,1,3,6";

    I need to find a way to isolate any given value (0, 1, 3, or 6) and remove it, so for example assume I want to remove "3" the string would then become = "0,1,6"
    Also, I need to be able to remove from the head and tail of the string, like remove the "0" or "6".

    Is there a good way to do this? Using .IndexOf and .SubString there seems to be a way (find the index right before and the index +2 to get to the next character) but I that will have issues at the head and tail, thought there might be a better way.
    Any clues?

  2. #2
    Join Date
    Feb 2004
    Posts
    541
    String is the wrong object to be using for this because it is immutable... ie once you create a string you can't alter it in any way. Any kind of altering would involve create a new string object. This isn't really a good way of doing things because it is not very efficient.

    If you take a look at the Java API for the Stringbuffer class you'll see all the methods you want. You can create the stringbuffer using the initial string as a parameter to the constructor, then it has a method delete() that will delete a substring of the string. The API is http://java.sun.com/j2se/1.4.2/docs/...ingBuffer.html

    As for actually finding the number you want it shouldn't be a problem if the string is always as simple as the one you posted. You can just inspect each character in the string, find out where the commas are, and you'll then know that everything between the commas is going to be a number. Put the string representation of the number in Integer.parseInt() and you'll end up with the number.

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


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center