2013-11-21 38 views
1
的字符串

我试图拿一个完整的字符串,并使用索引来打印它的每个部分。 我一直是这样的......分隔一个索引为

String example = "one, two, three, four" 
int comma = example.indexOf(',' , 0); 
    String output = example.substring(comma); 
    System.out.println(output); 

这将打印

,two,three,four 

我不能让它做别的......

+1

您需要使用'loop'。 –

回答

2

只有使用indexOf实现方法具d用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(); 

输出:一二三四

+0

谢谢!我只是添加了\ n来创建新行。 –

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]); 
} 
+0

谢谢,但我必须使用indexOf方法。 –

0

在String类中有一个方便的方法。 Sting#split

你只需用逗号分隔你的字符串,那就是你所需要的。

String example = "one, two, three, four"; 
String[] split = example.split(","); 
for (String string : split) { 
    System.out.println(string); 
} 

分割方法返回的分离和字符串的,我们只需要打印出来的array

附注:我用Enhanced for loop to iterate

+0

谢谢,但我必须使用indexOf方法。 –

+0

在循环中使用'indexOf'也可以将'String'分开。 – Masudul

+0

@Masud是的,单个问题可能有多种可能的解决方案。我没有在哪写*不可能* –

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; 
+0

谢谢,但我不得不使用indexOf方法。 –

+0

@ user2880779已编辑.... –

0

做这样

String example = "one, two, three, four" 
String[] output = example.split(','); 
for(String s:output){ 
    System.out.println(s); 
} 
+0

谢谢,但我必须使用indexOf方法。 –

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)); 
    } 
} 
相关问题