Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 7 of 7
  1. #1
    Regular Coder
    Join Date
    Oct 2011
    Posts
    106
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Split string ArrayList

    I need to split a string. Simple:
    Code:
    String s = "Hello-world";
    String str[] = new String[2];
    str = s.split("-");
    But, what happens when your string is user input?
    Code:
    String s = JOptionPane.showInputDialog(null, "text will be split at the spaces");
    //they enter "Hello-world,-my-name-is-Susie"
    String str[] = new String[2];
    str = s.split("-");
    This throws an out of bounds exception at 2.
    What about ArrayList()?
    Code:
    //with the same user input
    ArrayList<String> strings = new ArrayList<String>();
    strings.add(s.split("-"));
    The thing is that (for an ArrayList), there is no such thing as that last bit of code. What code that is real and does the job of strings.add(s.split("-")); for an ArrayList?

  • #2
    Regular Coder Apothem's Avatar
    Join Date
    Mar 2008
    Posts
    380
    Thanks
    36
    Thanked 25 Times in 25 Posts
    One solution is using an enhanced for loop:
    for(String sub : s.split("-")) { strings.add(sub); }

  • #3
    Senior Coder alykins's Avatar
    Join Date
    Apr 2011
    Posts
    1,806
    Thanks
    41
    Thanked 199 Times in 198 Posts
    maybe something like this...
    Code:
    string splitme = ""; //use this string to accept arguments
    
    .... elsewhere ...
    
    int _chars = 1; 
    if(splitme.length != 0){
    for(int i = 0; i<=splitme.length; i++){
      char evalchar = splitme.charAt(i);
      if(evalchar == "-")
        _chars++;
    }
    }
    
    string[] splitArray = new string[_chars];
    ... then do your split ...
    so what is going on here (and it may be flawed a bit since my J skills are growing )
    setting an int to be 1 by default so if the string contains no "split" char you don't end up trying to make a 0 length array- you will just get an array made with 1 spot; also your total amount of array that you will need to make will always be 1 more than how many split chars you have so it sets it up nicely.
    next going to take the string and if it is not length 0 (ie "") going to go through it and (i<=splitme.length) count how many split variables there are by using the .charAt() method. this points to a place on the string and looks to see what that char is, if it is our split char then we increment how many array slots we will be making and if not we move on and do nothing.

    I code C hash-tag .Net
    Reference: W3C W3CWiki .Net Lib
    Validate: html CSS
    Debug: Chrome FireFox IE

  • #4
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    ?
    String.split will return an array; you don't need to predeclare an array size to overwrite:
    PHP Code:
    String[] str s.split("-"); 
    Edit:
    Oh, and if you want a list, that can be done by using Arrays.asList.
    PHP Code:
    List<Stringal Arrays.asList(s.split("-")); 
    Last edited by Fou-Lu; 12-29-2011 at 01:52 PM.

  • Users who have thanked Fou-Lu for this post:

    Scriptr (12-29-2011)

  • #5
    Senior Coder alykins's Avatar
    Join Date
    Apr 2011
    Posts
    1,806
    Thanks
    41
    Thanked 199 Times in 198 Posts
    i thought in my other post you said you cannot do that in Java- in another thread I had posted (granted I was doing something different)
    *sidebar - sorry OP I don't mean to hijack thread but I feel info that I am asking is relevant to you as well*
    Ref thread
    so i had (and it was in ref to ant int[] but I assume same issue would have happened for string[])
    Code:
    string[] validatethis = null;
    and then later.....
    validatethis = mystring.split(".");
    So I assume that would have crashed out.. am I wrong on that assumption? or does it work in this case bc you are substantiating it while doing the split?
    String[] str = s.split("-");
    *just trying to work out the differences in why it works in one place and not the other- I am leaning towards bc you are substantiating w/ the split yes?

    I code C hash-tag .Net
    Reference: W3C W3CWiki .Net Lib
    Validate: html CSS
    Debug: Chrome FireFox IE

  • #6
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    String[] is just the datatype, as is int[]. You don't need to specify the size of it until you instantiate it. When an array is returned by something different, it can take the place of the placeholder.
    Simple look: T[] -> 4 byte pointer <- T[4] returned
    The T[] you declared is simply a pointer to the returned results of the T[4]. The pointer has been assigned, but in Java world I don't know if its a direct memory pointer or if it has multiple levels of indirection. I'd assume multiple levels.

    Your thread is different. String.split will return a String[], so you cannot just cast that into an int[] type. Without a defined size of the T[], it is assumed to be that of 0, so you cannot dereference it to write any data into it.
    So with your example you could have actually used:
    PHP Code:
    String[] octets args.getHostAddress().split("\\."); 
    The only way to cast it is by iterating it after the fact, which means you'll need to either do something immediately, store it in a collection, or use a pre-defined array size.

    Edit:
    Sorry, for a better explanation of the problem in your other thread:
    int[] i = null; is an int array without a size. Your error came from trying to use i[value], since this would never exist. This is why you needed to use a new int[4] for the size.
    Last edited by Fou-Lu; 12-29-2011 at 04:34 PM.

  • #7
    New to the CF scene
    Join Date
    Dec 2011
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts
    you can have a try...

    public static List splitString(String strInput, String strSplitor, boolean trim) {
    List listResult = new ArrayList();
    if (strInput == null) {
    return null;
    }
    int start = 0;
    int end = strInput.length();

    while (start < end) {
    int delimIdx = strInput.indexOf(strSplitor, start);

    if (delimIdx < 0) {
    String tok = strInput.substring(start);
    if (trim) {
    listResult.add(tok.trim());
    } else {
    listResult.add(tok);
    }
    start = end;
    } else {
    String tok = strInput.substring(start, delimIdx);
    if (trim) {
    listResult.add(tok.trim());
    } else {
    listResult.add(tok);
    }
    start = delimIdx + strSplitor.length();
    }
    }
    return listResult;
    }


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •