如何计算多个字符串长度

Cle*_*ier 3 java string algorithm

我有一个这样的字符串:

嘿,我的名字是$ name $; 我有$岁多岁,我喜欢玩$ sport $,我住的是$ country $!

我想在地图中返回$之间的每个单词的长度,例如,我的地图应该是:

  • 名字 - > 4
  • 年 - > 5
  • 运动 - > 5
  • 国家 - > 7

起初我想过在我的函数中进行递归调用,但是我没有办法做到这一点?

Edu*_*nis 5

您可以使用PatternMatcher进行匹配,这将返回所有匹配的实例,然后您可以迭代结果并添加到地图.

String x = "Hey my name is $name$; I have $years$ years old," + 
           "and I love play $sport$ and I live in $country$ !";
Pattern p = Pattern.compile("\\$\\w+\\$");
Matcher m = p.matcher(x);
Map<String, Integer> map = new LinkedHashMap<>();

while(m.find()) {
  String in = m.group().substring(1,m.group().length()-1);
  map.put(in, in.length());
}
Run Code Online (Sandbox Code Playgroud)