使用while循环、子字符串和indexOf的简单Java问题
我正在做一个学习Java的练习,我应该写一个方法,将单词“category:”后面的所有项目打印到屏幕上。这是我的尝试:使用while循环、子字符串和indexOf的简单Java问题,java,substring,indexof,Java,Substring,Indexof,我正在做一个学习Java的练习,我应该写一个方法,将单词“category:”后面的所有项目打印到屏幕上。这是我的尝试: public static void main(String[] args) { String str = "We have a large inventory of things in our warehouse falling in " + "the category:apperal and the
public static void main(String[] args) {
String str = "We have a large inventory of things in our warehouse falling in "
+ "the category:apperal and the slightly "
+ "more in demand category:makeup along with the category:furniture and _.";
printCategories(str);
}
public static void printCategories(String passedString) {
int startOfSubstring = passedString.indexOf(":") + 1;
int endOfSubstring = passedString.indexOf(" ", startOfSubstring);
String categories = passedString.substring(startOfSubstring,endOfSubstring);
while(startOfSubstring > 0) {
System.out.println(categories);
startOfSubstring = passedString.indexOf((":") + 1, passedString.indexOf(categories));
System.out.println(startOfSubstring);
System.out.println(categories);
}
}
因此,程序应打印:
上腹的化妆
家具 我的尝试是,程序应该打印它发现起始索引为“:”且结束索引为“”的子字符串。然后它再次做同样的事情,只是从变量str的最开始开始开始,这次它从找到的最后一个类别的开始开始 一旦不再有“:”被找到,indexOf(startOfSubstring的一部分)将返回-1,循环将终止。但是,在打印第一个类别之后,它会一直返回-1,并在找到下一个类别之前终止 这两条线:
System.out.println(startOfSubstring);
System.out.println(categories);
确认打印第一个类别后返回-1,最后一行确认categories变量仍定义为“apperal”。如果我把这行注释掉:
startOfSubstring=passedString.indexOf((“:”)+1,passedString.indexOf(categories))代码>
它将startOfSubstring返回为77。因此,这与该行有关,并试图更改indexOf方法中搜索位置的开始位置,导致它过早返回-1,但我无法理解为什么会发生这种情况。我花了几个小时想弄明白
请帮助:(我已经更正了(在评论中)您设置startOfSubstring的新值的地方
while(startOfSubstring > 0) { // better if you do startOfSubstring != -1 IMO
System.out.println(categories);
// this should be startOfSubstring = passedString.indexOf(":", startOfSubstring +1);
startOfSubstring = passedString.indexOf((":") + 1, passedString.indexOf(categories));
System.out.println(startOfSubstring);
System.out.println(categories);
}
该计划有几个问题:
您正在搜索passedString
以查找(“:”)+1
,这是字符串“:1”
,可能不是您想要的
您应该在循环中计算endOfSubstring
和categories
这可能接近您想要的:
public static void printCategories(String passedString) {
int startOfSubstring = passedString.indexOf(":") + 1;
while(startOfSubstring > 0) {
int endOfSubstring = passedString.indexOf(" ", startOfSubstring);
// If "category:whatever" can appear at the end of the string
// without a space, adjust endOfSubstring here.
String categories = passedString.substring(startOfSubstring, endOfSubstring);
// Do something with categories here, maybe print it?
// Find next ":" starting with end of category string.
startOfSubstring = passedString.indexOf(":", endOfSubstring) + 1;
}
}
这很有效!!非常感谢。我现在将对它进行更详细的分析,因为与旧代码相比,我仍然不清楚到底是什么让它起作用,但我会仔细检查并找出它。谢谢!!我想你的大部分问题是(“:”)+1
。你打算用调用indexOf
。“
,然后再加上1,但事实上,您将字符串“1”
附加到:“
给出”:1“
,然后将其传递到索引。