【发布时间】:2020-11-25 14:41:44
【问题描述】:
在我的作业中,禁止使用集合和任何数组。我们可以使用 String Tokenizer,但不允许使用 String 和 System 以外的任何其他类。此解决方案必须适用于任意数量的条目。
我有一个如下所示的字符串:
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;
}
我有这种方法,我使用子字符串方法删除字符串中的子字符串:
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
如果有人能帮我解决这个问题,我将不胜感激。
谢谢
【问题讨论】:
-
我对此不感兴趣,因为在现实生活中你会在这里使用
String#split,而不是迭代。 -
是的,我知道,但在我的项目中,我不能使用 char 数组或任何数组。