【问题标题】:identifying indices(java)识别索引(java)
【发布时间】:2011-11-11 01:27:56
【问题描述】:

这让我恶心..你能帮我解决这个问题吗?我的问题是识别我的java程序上的空格和它的索引,但我不知道如何识别索引(JAVA)。这是我的代码:

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;
     }
    }

谢谢。

【问题讨论】:

    标签: java whitespace indices


    【解决方案1】:
    if(Character.isWhitespace(str.charAt(i)))
    

    您已经充分利用了它。如果上述条件为真,则在 index i 处有空格字符。但是,如果您需要跟踪所有索引,请将索引 i 复制到 if 中的数组中。

    【讨论】:

      【解决方案2】:

      使用ArrayList 记录索引。这也消除了计数的需要,因为列表中的条目数就是出现的次数。

      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();
      

      【讨论】:

      • 为什么在System.out.print(i.toString() + " "); 中使用i.toString()?这将工作System.out.print(i + " ");简单且主要使用[在我看来]System.out.print(i);。最后也不需要System.out.println();
      • 虽然你是对的,前者是不需要的......无论如何它都会发生::shrug::。另一方面,后者是为了可读性。您的版本将打印类似于 Whitespace is located at indices: 251022 的内容,没有回车,而上面的代码打印 Whitespace is located at indices: 2 5 10 22
      • 哦!是的。没有注意到您使用的是print 而不是println。但仍然认为你应该删除 toString();这是不必要的。 ;-)
      • 迂腐点——在这种情况下,我更喜欢 LinkedList,因为列表必须动态调整大小,并且不需要有效的随机访问。我还将它声明为 List 而不是显式指定列表类型。
      • 是的..我在发布后想到了这一点,但决定离开它::shrug:: 在这种情况下,我认为这没什么大不了的。我可以争辩说,在真实的场景中,您可能想知道第三个空格在哪里。
      猜你喜欢
      • 2018-01-09
      • 2012-08-10
      • 2016-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-05
      • 2012-07-03
      相关资源
      最近更新 更多