codeeeeeNOT
codeeeeeNOT

Reputation: 133

How to delete a character from a string using java

I am trying to delete character at a time from a string in Java this is what I wrote

String word = "evelina";
char[] wordCharArr = word.toCharArray();

//Deleting one

for(int i = 0; i< wordCharArr.length; i++)
{
    String answer = word.subString(i);
    if(list.lookup(answer))
        perm.add(answer);
}

What this does is this:

evelina
velina
elina
lina
ina
na
a

But I need it to do this

evelina
velina
eelina
evlina
eveina
evelna
evelia
evelin

Upvotes: 1

Views: 366

Answers (1)

Jo&#227;o Silva
Jo&#227;o Silva

Reputation: 91299

At each iteration, you need to skip the i-th character:

for (int i = 0; i < wordCharArr.length; i++) {
  String answer = word.substring(0, i) + word.substring(i + 1);
  if (list.lookup(answer)) {
    perm.add(answer);
  }
}

Upvotes: 3

Related Questions