Removing value from split?

Discussion in 'Programming' started by HotDoctor, Jul 7, 2020.

  1. Title says everything I need
    i wil put an example

    Code (Java):

    String numbers = "one;two;tree;four;five;six";
    String[] splitting = numbers.split(";");

    //Question is, what about if I want remove the value "tree" from the split? and how to re-build the string
    //without this deleted value?
     
     
    #1 HotDoctor, Jul 7, 2020
    Last edited: Jul 7, 2020
  2. You can iterate the split strings in a for loop and checking that if the string is tree.
    Code (Java):
    int l = 0; // if you want to remove
    String[] s = numbers.split(";");
    for (String split : s) {
        l++;

        if (split.equals("tree")) {
           continue;
        }

        //yourcode
    }

    if (s[l].equals("tree")) {
       //codetoremove
    }
    If you want to keep the deleted value, create a new string array that contains the same array strings and create a new one from which you will remove it.
     
  3. Thanks alot, i will test it
     
  4. Strahan

    Benefactor

    I'd probably just use a List. Less code than the looping.
    Code (Text):
    List<String> data = Arrays.asList("one;two;tree;four;five;six".split(";"));
    data.remove("tree");
     
    • Agree Agree x 1
    • Friendly Friendly x 1
  5. it will remove the ";", right?

    thanks alot for the idea.
     
  6. Strahan

    Benefactor

    Well, that depends on your source data. If the data are coming in as a semicolon delimited string, then you still split on the semicolon just into a List rather than a String array. Lists allow easy removal by value. If you were building that delimited string yourself from other data, then yea, you could create the List and just add elements to it directly from the source. Hard to really say without knowing exactly what is going on in the data and code.