有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中使用子字符串删除部分字符串

在我的作业中,禁止使用集合和任何数组。我们可以使用字符串标记器,但不允许使用字符串和系统以外的任何其他类。此解决方案必须适用于任意数量的条目

我有一根绳子,看起来像这样:

1|Aaron|Peter|3063543030|john@gmail.com + "\n" 
2|Buffet|Anthony|3063543030|john@gmail.com + "\n" 
3|Dunty|Richard|3063543030|john@gmail.com 

我有一个小方法来达到下一个字符串索引:

 public static int nextIndex(int index, String carnet) {
        return carnet.indexOf("\n", index) +1;
        }

我有这样一种方法,使用substring方法删除字符串中的一个子字符串:

public static String deleteContactFromString (String idContact, String myString) {

        String stringModified = "";
        String myStringModified = "";

        String id = idContact.trim();

        if(!myString.isEmpty()) {

            int start = myString.indexOf(id + "|");

            if (start >= 0) {
            //Here I call the nextIndex method to get next string index
                int end = nextIndex(start, myString);
                
                stringModified = carnet.substring(0, start) + carnet.substring(end);
                myStringModified = stringModified;
                System.out.println("string modified " + myStringModified);
            } else {
                System.out.println("This contact doesnt exist");
                myStringModified = myString;
            }
        }

               return myStringModified;
    }

我的问题是,当myString中只有一个联系人时,我无法删除该索引,因为没有下一个索引。当我试图删除字符串的最后一个索引时,也会出现同样的问题

如果myString是这样的,并且只有一个联系人:

1|Aaron|Peter|3063543030|john@gmail.com + "\n" 

我不能删除那个索引

如果myString有更多联系人,而我试图删除最后一个索引,我也会遇到同样的问题:

1|Aaron|Peter|3063543030|john@gmail.com + "\n" 
2|Buffet|Anthony|3063543030|john@gmail.com + "\n" 
3|Dunty|Richard|3063543030|john@gmail.com <-- Can't be deleted

如果有人能帮我解决这个问题,我将不胜感激

谢谢


共 (0) 个答案