簡體   English   中英

提高效率以從Java中的字符串中刪除字符

[英]improve efficiencey to remove a character from a string in java

->如何在以下代碼中提高“從字符串中刪除字符的效率”:

import java.util.Scanner;

public class StringPractice {

public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter a String : ");
    String str;
    str=sc.nextLine();
    System.out.println("Enter char to remove : ");
    char ch=sc.nextLine().charAt(0);

    char[] a=new char[str.length()];
//  System.out.println("Parameters : Char : "+ch+"  String : "+str+"\n");

    StringPractice ob=new StringPractice();
    a=ob.removeChar(str,ch);
    String str1=new String(a);
    System.out.println("New String is : "+str1);
}
char[] removeChar(String a,char c){
    char[] ch=new char[a.length()];
    byte count=0;
    for(int i=0;i<a.length();i++){
        if(a.charAt(i)==c){
            count++; 
            continue;
        }
         ch[i-count]=a.charAt(i);
    }

    return ch; 
}
}

根據我的說法,您正在編寫代碼以刪除字符串中的字符,因此只需將其替換為空字符串即可:只需更改此代碼,就無需removeChar方法:

StringPractice ob=new StringPractice();
        a=ob.removeChar(str,ch);
        String str1=new String(a);

溶液

str = str.replace(ch, "");

替換所有情況:

 str = str.replaceAll("ch","");

內置的String函數replaceAll()刪除所有出現的內容, replace()刪除單個字符。

 string = string.replaceAll("c","");
 string = string.replace("c","");

您還可以使用可變的StringBuilder類。

StringBuilder sb =新的StringBuilder(inputString);

 public class RemoveString { public static void main (String args[]){ StringBuilder name= new StringBuilder("chandu"); int i= name.indexOf("n"); name.deleteCharAt(i); System.out.println(name.toString()); } 

暫無
暫無

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

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