-1

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 java.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.

Sumit
  • 736
  • 8
  • 26
pj llanes
  • 1
  • 2

2 Answers2

4

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();
Brian Roach
  • 76,169
  • 12
  • 136
  • 161
  • Why you are using `i.toString()` in `System.out.print(i.toString() + " ");`? This will work `System.out.print(i + " ");`. **OR** Simple and mostly used [in my opinion] `System.out.print(i);`. Also *no need* of `System.out.println();` at the end. – Harry Joy Sep 06 '11 at 07:00
  • While you're correct in that the former isn't needed ... it's going to happen anyway ::shrug::. The latter on the other hand, is for readability. Your version would print something akin to `Whitespace is located at indices: 251022` with no carriage return whereas the code above prints `Whitespace is located at indices: 2 5 10 22`. – Brian Roach Sep 06 '11 at 07:07
  • Oh! yes. Didn't noticed that you are using `print` and not `println`. But still thinks you should remove toString(); it is unnecessary. ;-) – Harry Joy Sep 06 '11 at 07:09
  • Pedantic point - I would favour LinkedList in this case as the list has to dynamically resize and there is no need for efficient random access. I would also declare it as List rather than explicitly specifying the list type. – Adamski Sep 06 '11 at 07:32
  • Yeah .. I thought of that after posting, but decided to leave it ::shrug:: In this case I don't think it's a huge deal. I could argue that in a real word scenario you might want to know where the third space is. – Brian Roach Sep 06 '11 at 07:38
2
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.

Mahesh
  • 34,573
  • 20
  • 89
  • 115