我正在尝试取一整个字符串,并使用索引来打印不同的每个部分。 我一直在尝试这样的事情......
String example = "one, two, three, four"
int comma = example.indexOf(',' , 0);
String output = example.substring(comma);
System.out.println(output);
打印
,two,three,four
我无法做任何其他事情......
答案 0 :(得分:2)
仅使用indexOf
loop
方法,您可以打印以逗号String
分隔的所有单独的,
。你不需要split
正则表达式。请看下面的例子。
String str = "one, two, three, four";
int lastIndex = 0;
int firstIndex=0;
while (lastIndex != -1) {
lastIndex = str.indexOf(',', lastIndex);
if (lastIndex != -1) {
System.out.print(str.substring(firstIndex, lastIndex));
if(lastIndex==str.lastIndexOf(',')){
System.out.print(str.substring(lastIndex));
}
lastIndex += 1;
}
firstIndex=lastIndex;
}
System.out.println();
输出:一二三四
答案 1 :(得分:2)
试试这个:
String example = "one, two, three, four";
for (int i = example.indexOf(", "); i != -1; i = example.indexOf(", ")) {
System.out.println(example.substring(0, i));
example = example.substring(i + 2);
}
System.out.println(example);
如果你喜欢递归:
public static void main(String[] args) {
String example = "one, two, three, four";
printSections(example);
}
public static void printSections(String word) {
int i = word.indexOf(", ");
if (i == -1) System.out.println(word);
else {
System.out.println(word.substring(0, i));
printSections(word.substring(i + 2));
}
}
答案 2 :(得分:0)
为什么不试试split()
?
String example = "one, two, three, four"
String[] temp = example.split(",");
for(int i=0;i<temp.length; i++){
System.out.println(temp[i]);
}
答案 3 :(得分:0)
String类中有一个方便的方法。 Sting#split
你只需用逗号分割你的字符串,这就是你所需要的。
String example = "one, two, three, four";
String[] split = example.split(",");
for (String string : split) {
System.out.println(string);
}
split方法返回分隔符和字符串的array
,我们只需要打印它们。
旁注:我使用了Enhanced for loop to iterate
答案 4 :(得分:0)
使用拆分
String example = "one, two, three, four";
for(String i:example.split(",")){
System.out.println(i);
}
使用IndexOf
String example = "one, two, three, four";
String output;
String temp = example;
int gIndex = 0;
int len = example.length();
example += ",";
for(int i=0 ; i<len;i+=gIndex+1){
gIndex = example.indexOf(",");
output = example.substring(0,gIndex);
System.out.println(output);
example = example.replace(output, "").replaceFirst(",", "");
}
example = temp;
答案 5 :(得分:0)
喜欢这个
String example = "one, two, three, four"
String[] output = example.split(',');
for(String s:output){
System.out.println(s);
}