简体   繁体   English

提高效率以从Java中的字符串中删除字符

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

--> How can I improve "efficiency of removing a character from a string" in the following code: ->如何在以下代码中提高“从字符串中删除字符的效率”:

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

According to me you are writing code to remove a character occurrence from a sting so just replace it with empty string: Just change this code there is no need of removeChar method: 根据我的说法,您正在编写代码以删除字符串中的字符,因此只需将其替换为空字符串即可:只需更改此代码,就无需removeChar方法:

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

SOl: 溶液

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

To replace All Occurrence: 替换所有情况:

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

inbuilt String function replaceAll() to remove all the occurrences and replace() to remove single character. 内置的String函数replaceAll()删除所有出现的内容, replace()删除单个字符。

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

You can also use the StringBuilder class which is mutable. 您还可以使用可变的StringBuilder类。

StringBuilder sb = new StringBuilder(inputString); 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