Remove a specific string from an array of string

前端 未结 5 1570
梦谈多话
梦谈多话 2020-12-03 13:45

I have an array like this:

String n[] = {\"google\",\"microsoft\",\"apple\"};

What I want to do is to remove \"apple\".

My problem

5条回答
  •  余生分开走
    2020-12-03 14:33

    Define "remove".

    Arrays are fixed length and can not be resized once created. You can set an element to null to remove an object reference;

    for (int i = 0; i < myStringArray.length(); i++)
    {
        if (myStringArray[i].equals(stringToRemove))
        {
            myStringArray[i] = null;
            break;
        }
    }
    

    or

    myStringArray[indexOfStringToRemove] = null;
    

    If you want a dynamically sized array where the object is actually removed and the list (array) size is adjusted accordingly, use an ArrayList

    myArrayList.remove(stringToRemove); 
    

    or

    myArrayList.remove(indexOfStringToRemove);
    

    Edit in response to OP's edit to his question and comment below

    String r = myArrayList.get(rgenerator.nextInt(myArrayList.size()));
    

提交回复
热议问题