首页 > 解决方案 > 不使用(子字符串)函数从字符串中删除特定字符

问题描述

出于学习目的,我需要在不使用 (substring) 函数的情况下从字符串中提取 'del' * 请注意字符串不是固定的,可以更改

我在下面的代码中解决了它,但我需要一些帮助以获得更好的代码,因为我的代码有很多行,我需要一个更好的解决方案。

public static String delDel(String str) {
    int num = 0;
    boolean s = false;
    char[] a = new char[str.length()];
    char[] b = new char[str.length()];
    for (int i = 0; i < str.length(); i++) {
        if ((str.charAt(i) == 'd')) {
            for (int j = 0; j < 1; j++) {
                a[j] = 'd';
            }
            num = i;
            s = true;
            break;
        }
    }

    if (s && (str.charAt(num + 1) == 'e') && (str.charAt(num + 2) == 'l')) {
        a[num] = str.charAt(num + 1);
        a[num + 1] = str.charAt(num + 2);
    }

    String t = new String(a).trim();
    System.out.println(t);

    if (t.equalsIgnoreCase("del")) {
        for (int i = 0; i < num; i++) {
            b[i] = str.charAt(i);
        }
        for(int j =1; j<str.length()-3;j++)
         {
            for (int ii = num + 3; ii < str.length(); ii++) {
            b[j] = str.charAt(ii);
            j++;
        }}
        String tt = new String(b).trim();
        return tt;
    }
    return str;

}

public static void main(String[] args) {
    System.out.println(delDel("adelrtyc"));
}

标签: java

解决方案


使用以下代码:

  String text = "adelrtyc";
  text = text.replaceAll("del","");

推荐阅读