identifying indices(java)
it makes me sick ..can you help me with this one? my problem is to identify the whitespaces on my java program and the indices of it but i dont know how to identify the indices(JAVA). heres my code:
import jav开发者_JAVA技巧a.util.*;
public class CountSpaces
{
public static void main (String[] args)
{
System.out.print ("Enter a sentence or phrase: ");
Scanner input=new Scanner(System.in);
String str=input.nextLine();
int count = 0;
int limit = str.length();
for(int i = 0; i < limit; ++i)
{
if(Character.isWhitespace(str.charAt(i)))
{
++count;
}
}
thanks ahead.
Use an ArrayList
to record the indices. This also eliminates the need for a count as the number of entries in the list is the number of occurrences.
ArrayList<Integer> whitespaceLocations = new ArrayList<Integer>();
for(int i = 0; i < limit; ++i)
{
if(Character.isWhitespace(str.charAt(i)))
{
whitespaceLocations.add(i);
}
}
System.out.println("Whitespace count: " + whitespaceLocations.size());
System.out.print("Whitespace is located at indices: ");
for (Integer i : whitespaceLocations)
{
System.out.print(i + " ");
}
System.out.println();
if(Character.isWhitespace(str.charAt(i)))
You already doing the most of it. If the above condition is true, then at index i you have the whitespace character. How ever, if you need to keep track of all the indices, then copy the index i to an array in the if
.
精彩评论