Question

Since strings are immutable, I'm trying to re-create it. I need to replace one of the letters.

for (int i = 0; i < mat.length(); i++){
    //there's more stuff here, but that'd require a lot more explaining
    //the following don't occur at every iteration
    //mat and s are always the same length though
    if (i == s.length())
        mat = mat.substring(0, i) + s.charAt(i);
    else
        mat = mat.substring(0, i) + s.charAt(i) + mat.substring(i + 1, mat.length());
}

Basically altering a letter of String mat with a letter of String s at the same index. Problem is if it's the last index, I would get an out of bounds error, so I've opted to use an if/else to take care of that.

But there's redundancy in that both conditions run the code:

mat = mat.substring(0, i) + s.charAt(i)

What's the best way to remove this redundancy? Thanks!

Was it helpful?

Solution

You want something like this (refactoring) ?

String optional = ""; 
if ((i != s.length()))
    optional=  mat.substring(i + 1, mat.length());

mat = mat.substring(0, i) + s.charAt(i) + optional

;

OTHER TIPS

If i=s.length() than last index will be i-1;

if (i == s.length())
mat = mat.substring(0, i) + s.charAt(i-1);// Use i-1 instead of i.
else
mat = mat.substring(0, i) + s.charAt(i) + mat.substring(i + 1, mat.length());

If value i is equals to the length of string s.

In your code s.charAt(i) is out of the array range. The max index to use should be i-1, which is for the last character.

pat = pat.substring(0, i) + s.charAt(i) + pat.substring(i + 1, pat.length());

by itself works........I'm not really sure why..... If the change need to happen at the first letter of the String, the first clause is just "", similarly if it's the last letter......shouldn't there be an out-of-bounds exception with the i+1?

update: just did a quick scratch program, as it turns out the inclusive index of the substring method does not return an out of bounds if it's only 1 past the last index.

Example:

    man ="what";

    System.out.println(man.substring(4, 4));

works just fine and outputs nothing. Console doesn't even pop up on eclipse if you use just .print

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top