150

为了在 Java 中访问字符串的单个字符,我们有String.charAt(2). 是否有任何内置函数可以删除java中字符串的单个字符?

像这样的东西:

if(String.charAt(1) == String.charAt(2){
   //I want to remove the individual character at index 2. 
}
4

24 回答 24

266

您还可以使用StringBuilder可变的类。

StringBuilder sb = new StringBuilder(inputString);

它具有 method deleteCharAt(),以及许多其他 mutator 方法。

只需删除需要删除的字符,然后得到如下结果:

String resultString = sb.toString();

这避免了创建不必要的字符串对象。

于 2012-11-14T19:54:38.923 回答
94

您可以使用名为 replace 的 Java String 方法,它将所有匹配第一个参数的字符替换为第二个参数:

String a = "Cool";
a = a.replace("o","");
于 2013-12-18T18:00:26.050 回答
84

一种可能:

String result = str.substring(0, index) + str.substring(index+1);

请注意,结果是一个新的字符串(以及两个中间字符串对象),因为 Java 中的字符串是不可变的。

于 2012-11-14T19:44:42.243 回答
17
String str = "M1y java8 Progr5am";

删除字符()

StringBuilder build = new StringBuilder(str);
System.out.println("Pre Builder : " + build);
    build.deleteCharAt(1);  // Shift the positions front.
    build.deleteCharAt(8-1);
    build.deleteCharAt(15-2);
System.out.println("Post Builder : " + build);

代替()

StringBuffer buffer = new StringBuffer(str);
    buffer.replace(1, 2, ""); // Shift the positions front.
    buffer.replace(7, 8, "");
    buffer.replace(13, 14, "");
System.out.println("Buffer : "+buffer);

字符[]

char[] c = str.toCharArray();
String new_Str = "";
    for (int i = 0; i < c.length; i++) {
        if (!(i == 1 || i == 8 || i == 15)) 
            new_Str += c[i];
    }
System.out.println("Char Array : "+new_Str);
于 2015-09-24T09:31:36.550 回答
16

不,因为 Java 中的字符串是不可变的。您必须创建一个新字符串来删除您不想要的字符。

要替换stringc中索引位置的单个字符,请执行以下操作,并记住将创建一个新字符串:idxstr

String newstr = str.substring(0, idx) + str.substring(idx + 1);
于 2012-11-14T19:43:54.430 回答
8

考虑以下代码:

public String removeChar(String str, Integer n) {
    String front = str.substring(0, n);
    String back = str.substring(n+1, str.length());
    return front + back;
}
于 2015-09-23T18:52:39.027 回答
5

要修改字符串,请阅读 StringBuilder,因为它是可变的,除了不可变的字符串。可以在这里找到不同的操作https://docs.oracle.com/javase/tutorial/java/data/buffers.html。下面的代码片段创建一个 StringBuilder,然后附加给定的 String,然后从 String 中删除第一个字符,然后将其从 StringBuilder 转换回 String。

StringBuilder sb = new StringBuilder();

sb.append(str);
sb.deleteCharAt(0);
str = sb.toString();
于 2019-08-27T17:37:45.353 回答
4

您也可以使用(巨大的)正则表达式机器。

inputString = inputString.replaceFirst("(?s)(.{2}).(.*)", "$1$2");
  • "(?s)" -告诉正则表达式像普通字符一样处理换行符(以防万一)。
  • "(.{2})" -组 $1 正好收集 2 个字符
  • "." -索引 2 处的任何字符(被挤出)。
  • "(.*)" -组 $2 收集输入字符串的其余部分。
  • "$1$2" -将 $1 组和 $2 组放在一起。
于 2014-07-30T21:19:27.380 回答
3

通过使用 replace 方法,我们可以更改字符串的单个字符。

string= string.replace("*", "");
于 2014-11-01T11:11:31.533 回答
2

如果要从特定int索引处的String str中删除 char :

    public static String removeCharAt(String str, int index) {

        // The part of the String before the index:
        String str1 = str.substring(0,index);

        // The part of the String after the index:            
        String str2 = str.substring(index+1,str.length());

        // These two parts together gives the String without the specified index
        return str1+str2;

    }
于 2019-02-03T19:44:11.900 回答
1

使用 String 类的 replaceFirst 函数。您可以使用许多替换功能的变体。

于 2012-11-14T19:44:40.143 回答
1

如果您需要对字符删除进行一些逻辑控制,请使用此

String string = "sdsdsd";
char[] arr = string.toCharArray();
// Run loop or whatever you need
String ss = new String(arr);

如果您不需要任何此类控制,则可以使用 Oscar orBhesh 提到的。他们是正确的。

于 2012-11-14T20:15:08.030 回答
1

从字符串中删除字符的最简单方法

String str="welcome";
str=str.replaceFirst(String.valueOf(str.charAt(2)),"");//'l' will replace with "" 
System.out.println(str);//output: wecome
于 2015-08-08T19:27:54.467 回答
1
public class RemoveCharFromString {
    public static void main(String[] args) {
        String output = remove("Hello", 'l');
        System.out.println(output);
    }

    private static String remove(String input, char c) {

        if (input == null || input.length() <= 1)
            return input;
        char[] inputArray = input.toCharArray();
        char[] outputArray = new char[inputArray.length];
        int outputArrayIndex = 0;
        for (int i = 0; i < inputArray.length; i++) {
            char p = inputArray[i];
            if (p != c) {
                outputArray[outputArrayIndex] = p;
                outputArrayIndex++;
            }

        }
        return new String(outputArray, 0, outputArrayIndex);

    }
}
于 2016-03-19T02:05:58.643 回答
1

在大多数用例中,使用StringBuilderorsubstring是一种好方法(正如已经回答的那样)。但是,对于性能关键代码,这可能是一个不错的选择。

/**
 * Delete a single character from index position 'start' from the 'target' String.
 * 
 * ````
 * deleteAt("ABC", 0) -> "BC"
 * deleteAt("ABC", 1) -> "B"
 * deleteAt("ABC", 2) -> "C"
 * ````
 */
public static String deleteAt(final String target, final int start) {
    return deleteAt(target, start, start + 1);
} 


/**
 * Delete the characters from index position 'start' to 'end' from the 'target' String.
 * 
 * ````
 * deleteAt("ABC", 0, 1) -> "BC"
 * deleteAt("ABC", 0, 2) -> "C"
 * deleteAt("ABC", 1, 3) -> "A"
 * ````
 */
public static String deleteAt(final String target, final int start, int end) {
    final int targetLen = target.length();
    if (start < 0) {
        throw new IllegalArgumentException("start=" + start);
    }
    if (end > targetLen || end < start) {
        throw new IllegalArgumentException("end=" + end);
    }
    if (start == 0) {
        return end == targetLen ? "" : target.substring(end);
    } else if (end == targetLen) {
        return target.substring(0, start);
    }
    final char[] buffer = new char[targetLen - end + start];
    target.getChars(0, start, buffer, 0);
    target.getChars(end, targetLen, buffer, start);
    return new String(buffer);
}
于 2017-09-03T10:31:15.817 回答
1

*您可以使用 StringBuilder 和 deletecharAt 删除字符串值。

String s1 = "aabc";
StringBuilder sb = new StringBuilder(s1);
for(int i=0;i<sb.length();i++)
{
  char temp = sb.charAt(0);
  if(sb.indexOf(temp+"")!=1)
  {                             
    sb.deleteCharAt(sb.indexOf(temp+""));   
  }
}
于 2017-11-06T14:28:42.917 回答
1

是的。我们有内置函数来删除java中字符串的单个字符,即deleteCharAt

例如,

public class StringBuilderExample 
{
   public static void main(String[] args) 
   {
      StringBuilder sb = new StringBuilder("helloworld");
      System.out.println("Before : " + sb);
      sb = sb.deleteCharAt(3);
      System.out.println("After : " + sb);
   }
}

输出

Before : helloworld
After : heloworld
于 2018-06-28T13:06:27.197 回答
1

要从给定字符串中删除单个字符,请找到我的方法,希望它有用。我已经使用 str.replaceAll 来删除字符串,但是它们有很多方法可以从给定的字符串中删除字符,但我更喜欢 replaceall 方法。

删除字符的代码:

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;


public class Removecharacter 
{

    public static void main(String[] args) 
    {
        String result = removeChar("Java", 'a');
        String result1 = removeChar("Edition", 'i');

         System.out.println(result + " " + result1);

    }


    public static String removeChar(String str, char c) {
        if (str == null)
        {
            return null;
        }
        else
        {   
        return str.replaceAll(Character.toString(c), "");
        }
    }


}

控制台图像:

请找到控制台的附加图像,

在此处输入图像描述

感谢您的提问。:)

于 2019-06-22T09:54:32.280 回答
0
public static String removechar(String fromString, Character character) {
    int indexOf = fromString.indexOf(character);
    if(indexOf==-1) 
        return fromString;
    String front = fromString.substring(0, indexOf);
    String back = fromString.substring(indexOf+1, fromString.length());
    return front+back;
}
于 2015-10-18T01:38:36.350 回答
0
           BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
   String line1=input.readLine();
   String line2=input.readLine();
         char[]  a=line2.toCharArray();
          char[] b=line1.toCharArray();
           loop: for(int t=0;t<a.length;t++) {

            char a1=a[t];
           for(int t1=0;t1<b.length;t1++) {
               char b1=b[t1];  
               if(a1==b1) {
                   StringBuilder sb = new StringBuilder(line1);
                   sb.deleteCharAt(t1);
                   line1=sb.toString();
                   b=line1.toCharArray();
                   list.add(a1);
                   continue  loop;   
               }


            }
于 2016-09-19T06:08:03.890 回答
0

当我遇到这类问题时,我总是会问:“Java 大师会做什么?” :)

在这种情况下,我会通过查看String.trim().

这是该实现的外推,允许使用更多的修剪字符。

但是,请注意,原始修剪实际上删除了所有字符<= ' ',因此您可能必须将其与原始字符组合以获得所需的结果。

String trim(String string, String toTrim) {
    // input checks removed
    if (toTrim.length() == 0)
        return string;

    final char[] trimChars = toTrim.toCharArray();
    Arrays.sort(trimChars);

    int start = 0;
    int end = string.length();

    while (start < end && 
        Arrays.binarySearch(trimChars, string.charAt(start)) >= 0)
        start++;

    while (start < end && 
        Arrays.binarySearch(trimChars, string.charAt(end - 1)) >= 0)
        end--;

    return string.substring(start, end);
}
于 2018-05-05T19:00:09.287 回答
0
public String missingChar(String str, int n) {
  String front = str.substring(0, n);

// Start this substring at n+1 to omit the char.
// Can also be shortened to just str.substring(n+1)
// which goes through the end of the string.

String back = str.substring(n+1, str.length());
  return front + back;
}
于 2018-07-13T05:01:27.393 回答
0

我刚刚实现了这个实用程序类,它从 String 中删除一个字符或一组字符。我认为它很快,因为不使用正则表达式。我希望它可以帮助某人!

package your.package.name;

/**
 * Utility class that removes chars from a String.
 * 
 */
public class RemoveChars {

    public static String remove(String string, String remove) {
        return new String(remove(string.toCharArray(), remove.toCharArray()));
    }

    public static char[] remove(final char[] chars, char[] remove) {

        int count = 0;
        char[] buffer = new char[chars.length];

        for (int i = 0; i < chars.length; i++) {

            boolean include = true;
            for (int j = 0; j < remove.length; j++) {
                if ((chars[i] == remove[j])) {
                    include = false;
                    break;
                }
            }

            if (include) {
                buffer[count++] = chars[i];
            }
        }

        char[] output = new char[count];
        System.arraycopy(buffer, 0, output, 0, count);

        return output;
    }

    /**
     * For tests!
     */
    public static void main(String[] args) {

        String string = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG";
        String remove = "AEIOU";

        System.out.println();
        System.out.println("Remove AEIOU: " + string);
        System.out.println("Result:       " + RemoveChars.remove(string, remove));
    }
}

这是输出:

Remove AEIOU: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
Result:       TH QCK BRWN FX JMPS VR TH LZY DG
于 2020-07-25T16:30:55.100 回答
-2

例如,如果你想计算字符串中有多少个 a,你可以这样做:

if (string.contains("a"))
{
    numberOf_a++;
    string = string.replaceFirst("a", "");
}
于 2013-10-17T23:02:57.150 回答