java - 如何创建一个查找最后一个匹配项的字符串数组程序?

标签 java arrays string match

我正在尝试创建一个字符串数组程序来查找最后一个匹配项。例如,当询问长度为 3 的最后一个单词时,代码应将“was”定位在索引 7 处。这是我到目前为止所拥有的,但我不确定如何确保代码返回最后一个匹配的位置:

   public static void main(String[] args)
   {
    String[] words = { "Mary", "had", "a", "little", "lamb",
                     "it's", "fleece", "was", "white", "as",
                     "snow" };

   Scanner in = new Scanner(System.in);
  System.out.print("Word length: ");
  int wordLength = in.nextInt();

  boolean found = false;
  int pos = 0; 
  while (!found)
  {
     if (wordLength == words[pos].length())
     {
        pos++;
     }
     else
     {
        found = true;
     }
  }

  if (pos > 0)
  {
     System.out.println("Found " + words[pos] + " at position " + pos);
  }
  else
  {
     System.out.println("No word of length " + wordLength);
  }
}

最佳答案

public static void main(String[] args)
{
  String[] words = { "Mary", "had", "a", "little", "lamb",
                     "it's", "fleece", "was", "white", "as",
                     "snow" };

  Scanner in = new Scanner(System.in);
  System.out.print("Word length: ");
  int wordLength = in.nextInt();

  boolean found = false;
  int pos;
  for(int i = words.length-1 ; i >= 0 ; i--)
  {
     if (wordLength == words[i].length())
     {
        pos =i;
        found = true;
        break;
     }
  }

  if (found)
  {
     System.out.println("Found " + words[pos] + " at position " + pos);
  }
  else
  {
     System.out.println("No word of length " + wordLength);
  }
}

关于java - 如何创建一个查找最后一个匹配项的字符串数组程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45182386/

相关文章:

java - 从现有的 byte[] 生成新的 byte[]

javascript - 更改 JSON 对象格式

c - 基本动态内存和数组指针

C# 将 XML 存储到字符串中

ruby - 正则表达式匹配 string1,除非前面有 string2

c++ - 在静态常量成员数组中将 char 类型转换为字符串

java - 如何同步围绕方法定义的 Java 方面?

java - 搜索并替换没有大括号的 if 语句以包含大括号

c# - 使用 LINQ 迭代字符串集合

java - 如何指定在终端使用哪个版本的 Java?