簡體   English   中英

從字符串中刪除字符

[英]Remove char from String

我想從String刪除一個字母-但是只出現一次該字母:

例如:如果我的單詞是"aaba"而我想刪除一個'a'

輸出將為"aba" -僅刪除第一個'a' (不是所有的'a'

我想出了這個:

String word = "aaba"
String newWord = word.replace(a, "");

問題是newWord='b'而不是'aba'

有人可以幫忙嗎? 由於某種原因,我很難解決這個看似簡單的問題。 解決此問題的最佳方法是什么?

我需要創建某種ArrayList嗎?

public String replace(char oldChar,char newChar)將用newChar替換此字符串中所有出現的oldChar。

您應該考慮使用public String replaceFirst(String regex,String replacement) ,它用給定的替換項替換與給定的正則表達式匹配的該字符串的第一個子字符串。

String word = "aaba"
String newWord = word.replaceFirst(a, "");

您首先需要使用indexof() metohd找到首次出現的索引,然后可以通過substring()方法找到目標char之前和之后的文本,最后需要使用concat()附加它們。

Str.replaceFirst()也很好用

字符串replaceFirst()方法

公共字符串replaceFirst(字符串正則表達式,字符串替換)

參數:

以下是參數的詳細信息:

regex -- the regular expression to which this string is to be matched.

replacement -- the string which would replace found expression.

 public static void main(String[] args) {
        String word = "aaba";
        String newWord = word.replaceFirst("a", "");
        System.out.println(newWord);
    }

產量

aba

您可以選擇使用public String replaceFirst(String regex, String replacement)

regex-這是該字符串要匹配的正則表達式。
替換-這是每個匹配項要替換的字符串。

由於在您的代碼中,您只想替換第一次出現的重復字符,因此可以將其替換為空白,如下面的代碼。

String word = "aaba" 
String newWord = word.replaceFirst(a, "");

暫無
暫無

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

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