Java – how to calculate the length of multiple strings
•
Java
I have a string like this:
Hey, my name is $name $; I'm over $years old. I like playing $sport $. I live in $country $!
I want to return the length of each word between $in the map. For example, my map should be:
>Name – > 4 > years – > five > Sports – > five > countries – > 7
At first I thought about making recursive calls in my functions, but I couldn't do that?
Solution
You can use pattern and matcher to match, which will return all matching instances, and then you can iterate the results and add them to the map
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()); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码