简体   繁体   中英

Wrong Answer with Java

I'm a student that is learning Java, and I have this code:

lletres = lletres.replace(lletres.charAt(2), codi.charAt(codi.indexOf(lletres.charAt(2)) + 1));

lletres is a string, and it's like this

lletres = "BBB"

The result is "CCC" and I only want to change the last B, so the result can be like this: "BBC".

Reading the documentation for String.replace should explain what happened here (I marked the relevant part in bold):

Returns a string resulting from replacing all occurrences of oldChar in this string with newChar .

One way to solve it is to break the string up to the parts you want and then put it back together again. Eg:

lletres =  lletres.substring(0, 2) + (char)(lletres.charAt(2) + 1);

As others pointed replace() will replace all the occurrences which matched.

So, instead you can make use of replaceFirst() which will accept the regx

lletres = lletres.replaceFirst( lletres.charAt( 2 ) + "$", (char) ( lletres.charAt( 2 ) + 1 ) + "" )

You could use StringBuilder for your purpose:

String lletres = "BBB";
String codi = "CCC";

StringBuilder sb = new StringBuilder(lletres);
sb.setCharAt(2, codi.charAt(codi.indexOf(lletres.charAt(2)) + 1));
lletres = sb.toString();

If you need to change only the last occurrence in the string, you need to split the string into parts first. I hope following snippet will be helpful to you.

String lletres = "BBB";
int lastIndex = lletres.lastIndexOf('B');
lletres = lletres.substring(0, lastIndex) + 'C' + lletres.substring(lastIndex+1);

This code will find index of last letter B and stores it in lastIndex. Then it splits the string and replaces that B letter with C letter.

Please keep in mind that this snippet doesn't check whether or not the letter B is present in the string.

With slight modification you can get it to replace whole parts of the string, not only letters. :)

Try this one.

class Rplce
{
public static void main(String[] args)
{
    String codi = "CCC";
String lletres = "BBB";
int char_no_to_be_replaced = 2;
lletres = lletres.substring(0,char_no_to_be_replaced ) + codi.charAt(codi.indexOf(lletres.charAt(char_no_to_be_replaced )) + 1) + lletres.substring(char_no_to_be_replaced + 1);
System.out.println(lletres);
}
}

用它代替最后一个字符

  lletres = lletres.replaceAll(".{1}$", String.valueOf((char) (lletres.charAt(2) + 1)));

suppose you have dynamic value at last index and you want to replace that value will increasing one then use this code

   String lletres = "BBB";
   int atIndex = lletres.lastIndexOf('B');
   char ReplacementChar = (char)(lletres.charAt(lletres.lastIndexOf('B'))+1);
   lletres= lletres.substring(0, atIndex)+ReplacementChar;
   System.out.println(lletres);

output

BBC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM