Luis
Luis

Reputation: 41

Deleting an extra space from a particular element in an array

I am a new to Java developing and going to school, I am stuck on this assignment and was hoping if you could point me in the right direction, I have an array and in the array there is an element " saw ", how could I delete the extra space there when I insert into a stringbuilder. I tried the delete() but the problem is if the elements are changed it needs to continue working properly. Here is my code, any feedback would be appreciated.

  String[] tools = {"hammer", "NAIL", " saw ", "Screw"};

    StringBuilder sb = new StringBuilder("We need ");



    for(int i = tools.length - 1; i >= 0; i--){
        if(i != 3){
            sb.append("s," + tools[i].toLowerCase());
        }
        else{
            sb.append(tools[i].toLowerCase());
        }

    }


    System.out.println(sb.toString() + "s and a lot of time.");
}

}

Upvotes: 1

Views: 72

Answers (3)

FSm
FSm

Reputation: 2057

If I'm not misunderstood,

    if(i != 3)
    {
        sb.append("s," + tools[i].toLowerCase().trim());
    }
    else{
        sb.append(tools[i].toLowerCase().trim());
      }

Upvotes: 0

rathna
rathna

Reputation: 1083

String class has trim method.You can use tools[i].trim() to remove spaces and continue appending.It will ignore if no spaces.

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 121998

You should trim() it

 if(i != 3){
            sb.append("s," + tools[i].toLowerCase().trim());
        }
        else{
            sb.append(tools[i].toLowerCase().trim());
        }

Upvotes: 3

Related Questions