簡體   English   中英

Java錯誤答案

[英]Wrong Answer with Java

我是一個正在學習Java的學生,並且我有以下代碼:

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

lletres是一個字符串,就像這樣

lletres = "BBB"

結果是“ CCC”,我只想更改最后一個B,所以結果可以像這樣:“ BBC”。

閱讀String.replace的文檔應該解釋這里發生了什么(我用粗體標記了相關部分):

返回一個字符串,該字符串是用newChar替換此字符串中所有出現oldChar newChar

解決該問題的一種方法是將字符串分解成所需的部分,然后再次將其放回原處。 例如:

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

正如其他人指出的那樣, replace()將替換所有匹配的事件。

因此,您可以使用replaceFirst()來接受regx

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

您可以將StringBuilder用於您的目的:

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();

如果只需要更改字符串中的最后一個出現,則需要先將字符串拆分成多個部分。 希望以下摘錄對您有所幫助。

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

此代碼將找到最后一個字母B的索引,並將其存儲在lastIndex中。 然后,它將字符串拆分,並將該B字母替換為C字母。

請記住,此代碼段不檢查字符串中是否存在字母B。

稍加修改,您就可以替換字符串的整個部分,而不僅僅是字母。 :)

試試這個。

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)));

假設您在最后一個索引處具有動態值,並且您想要替換該值將增加一個值,然后使用此代碼

   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);

產量

BBC

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM