如何使字符串比较具有包容性?

huangapple go评论84阅读模式
英文:

How to make string comparison inclusive?

问题

我有一个包含单词及其定义的TreeMap。我正在编写一个方法,该方法将返回在范围内的所有单词及其定义;它接受两个参数:string beginstring end

以下是我目前的代码:
我在函数外部初始化了一个TreeMap:

Map<String, List<String>> wordDictionary = new TreeMap<String, List<String>>();
Set<String> wordSet = wordDictionary.keySet();
Iterator<String> iterator = wordSet.iterator();
while (iterator.hasNext()) {
  String current = iterator.next();
  if (
    (current.compareToIgnoreCase(begin) >= 0) &&
    (current.compareToIgnoreCase(end) <= 0)
  ) {
    List<String> defList = wordDictionary.get(current);
    System.out.println(current);
    Iterator<String> itr2 = defList.iterator();
    while (itr2.hasNext()) {
      System.out.println(" " + itr2.next());
    }
  }
}

示例用法: "List a b"
该方法应返回从 ab 的所有单词。
然而,我的方法返回的是在 ab 之间的所有单词;它不包括以 ab 开头的单词。

我尝试调整 if 语句为

if (
    (current.compareToIgnoreCase(begin) > 0) &&
    (current.compareToIgnoreCase(end) < 0)
  )

但那也不起作用。它会显示以 begin 开头但不以 end 开头的单词。希望这能理解。

英文:

I have a TreeMap that contains words and its definition(s). I'm writing a method that will return all the word and its definitions with a range; it takes in two parameters: string begin and string end.
Here's what I have so far
I initialized a TreeMap outside of the function:

Map&lt;String, List&lt;String&gt;&gt; wordDictionary = new TreeMap&lt;String, List&lt;String&gt;&gt;();
Set&lt;String&gt; wordSet = wordDictionary.keySet();
    Iterator&lt;String&gt; iterator = wordSet.iterator();
    while (iterator.hasNext()) {
      String current = iterator.next();
      if (
        (current.compareToIgnoreCase(begin) &gt;= 0) &amp;&amp;
        (current.compareToIgnoreCase(end) &lt;= 0)
      ) {
        List&lt;String&gt; defList = wordDictionary.get(current);
        System.out.println(current);
        Iterator&lt;String&gt; itr2 = defList.iterator();
        while (itr2.hasNext()) {
          System.out.println(&quot; &quot; + itr2.next());
        }
      }
    }

Example use: "List a b"
The method should return all words from a to b <br>
However my method returns all words between a and b; it excludes words starting with a and b.

I tried tweaking the if case to

if (
        (current.compareToIgnoreCase(begin) &gt; 0) &amp;&amp;
        (current.compareToIgnoreCase(end) &lt; 0)
      )

but that doesn't work either. It displays words starting with begin but not end. Hope that makes sense.

答案1

得分: 3

如果你有一个 TreeMap,使用它的 subMap() 方法!

Map<String, List<String>> range = wordDictionary.subMap(begin, true, end, true);

然后遍历整个映射。

第 2 和第 4 参数控制范围的结束是否包含在内 - 看起来你想要两端都包含,但如果不是这样,将第 4 参数改为 false

——

顺便说一下,由于你不是打印单词,只是定义,你的代码可以简化为:

wordDictionary.subMap(begin, true, end, true).values().stream()
    .flatMap(List::stream)
    .forEach(System.out::println);

如果你想在缩进的定义之前也打印单词:

wordDictionary.subMap(begin, true, end, true).entrySet().stream()
    .peek(e -> System.out.println(e.getKey()))
    .map(Map.Entry::getValue)
    .flatMap(List::stream)
    .forEach(d -> System.out.println(" " + d));
英文:

If you have a TreeMap, use its subMap() method!

Map&lt;String, List&lt;String&gt;&gt; range = wordDictionary.subMap(begin, true, end, true);

And iterate over the whole map.

The 2<sup>nd</sup> and 4<sup>th</sup> parameters control if the range ends are inclusive or not - it seems you want inclusive both ends, but if not change the 4<sup>th</sup> parameter to false.

——

By the way, since you are not printing the word, just the definitions, your code can be reduced to:

wordDictionary.subMap(begin, true, end, true).values().stream()
.flatMap(List::stream)
.forEach(System.out::println);

If you wanted to also print the word before indented definitions:

wordDictionary.subMap(begin, true, end, true).entrySet().stream()
.peek(e -&gt; System.out.println(e.getKey()))
.map(Map.Entry::getValue)
.flatMap(List::stream)
.forEach(d -&gt; System.out. println(&quot; &quot; + d);

答案2

得分: 2

你可以通过类似以下方式使TreeMap的subMap在两端都是闭区间:

TreeMap<String, String> map = new TreeMap<>();

map.put("abc", "a");
map.put("efg", "a");
map.put("hij", "v");
map.put("rst", "o");

String start = "a";
String end = "e";

int idx = end.length() - 1;

// 修改结束字符串的最后一个字符为包含在内。
StringBuilder sb = new StringBuilder(end);
char c = sb.charAt(sb.length() - 1);
sb.setCharAt(sb.length() - 1, (char) (c + 1));
end = sb.toString();

Map<String, String> words =
    map.subMap(start, true, end, false);

System.out.println(words);

输出

{abc=a, efg=a}

这会递增结束字符串的最后一个字符,以包含小于那个字符的任何内容。

英文:

You could make the subMap of TreeMap inclusive on both ends by doing something like the following:

TreeMap&lt;String,String&gt; map = new TreeMap&lt;&gt;();
         
map.put(&quot;abc&quot;,&quot;a&quot;);		
map.put(&quot;efg&quot;,&quot;a&quot;);		 
map.put(&quot;hij&quot;,&quot;v&quot;);		 
map.put(&quot;rst&quot;,&quot;o&quot;);

String start = &quot;a&quot;;
String end = &quot;e&quot;;

int idx = end.length() - 1;

// modify last character of end to be inclusive.
 StringBuilder sb = new StringBuilder(end);
 char c = sb.charAt(sb.length()-1);
 sb.setCharAt(sb.length()-1, (char)(c+1));
 end = sb.toString();

Map&lt;String, String&gt; words =
		map.subMap(start, true, end,false);

System.out.println(words);

Prints

{abc=a, efg=a}

It increments the last character of the ending string so as to include anything less than that.

答案3

得分: 2

获取所有以&#39;b&#39;开头的键,使用 subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) 方法:

TreeMap<String, String> wordDictionary = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
wordDictionary.put("A", "1");
wordDictionary.put("Abc", "2");
wordDictionary.put("Axe", "3");
wordDictionary.put("B", "4");
wordDictionary.put("Bee", "5");
wordDictionary.put("C", "6");
wordDictionary.put("Car", "7");

NavigableMap<String, String> bdict = wordDictionary.subMap("b", true, "c", false);
System.out.println(bdict);
System.out.println(bdict.keySet());

// Alternative
NavigableSet<String> bwords = wordDictionary.navigableKeySet().subSet("b", true, "c", false);
System.out.println(bwords);

输出

{B=4, Bee=5}
[B, Bee]
[B, Bee]
英文:

To get all keys that start with e.g. &#39;b&#39;, use subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive):

TreeMap&lt;String, String&gt; wordDictionary = new TreeMap&lt;&gt;(String.CASE_INSENSITIVE_ORDER);
wordDictionary.put(&quot;A&quot;, &quot;1&quot;);
wordDictionary.put(&quot;Abc&quot;, &quot;2&quot;);
wordDictionary.put(&quot;Axe&quot;, &quot;3&quot;);
wordDictionary.put(&quot;B&quot;, &quot;4&quot;);
wordDictionary.put(&quot;Bee&quot;, &quot;5&quot;);
wordDictionary.put(&quot;C&quot;, &quot;6&quot;);
wordDictionary.put(&quot;Car&quot;, &quot;7&quot;);

NavigableMap&lt;String, String&gt; bdict = wordDictionary.subMap(&quot;b&quot;, true, &quot;c&quot;, false);
System.out.println(bdict);
System.out.println(bdict.keySet());

// Alternative
NavigableSet&lt;String&gt; bwords = wordDictionary.navigableKeySet().subSet(&quot;b&quot;, true, &quot;c&quot;, false);
System.out.println(bwords);

Output

{B=4, Bee=5}
[B, Bee]
[B, Bee]

huangapple
  • 本文由 发表于 2020年8月21日 01:17:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/63510160.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定