Click here to Skip to main content
15,885,914 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have c# code which is
C#
var matches = Regex.Split(sentence.ToLower(), "\\b").Intersect(keyword)
string matchWord= String.Join(" ", matches);
int countWord = Regex.Matches(matchWord, @"[A-Za-z0-9]+").Count;

this code will match the matches word and count it.

How do I convert it to java?

i want to match sentence with keyword and the output will be the keyword that matches.

example :
keyword : "buy", "want", "sell"
input : I want to buy some apple.
output : buy want
output2 : 2

What I have tried:

Java
List<String> keyword = Arrays.asList("word1", "word2", "word3");

Scanner in = new Scanner(System.in);
String sentence = in.nextLine();

String patternString = "\\b(" + StringUtils.join(keyword, "|") + ")\\b";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(sentence);


the .join part is error and i don't know why. It said "cannot find symbol" when I hover over it.
i have no idea how to convert .count into java, because all I know for regex fuction is boolean String.Matches().
Posted
Updated 13-Apr-16 21:31pm
v5

 
Share this answer
 
String strArray[] = sentence.split("\\b")
String result = String.join("...", strArray);
System.out.println(result);


is it not the same ??




http://www.dotnetperls.com/join-java[^]
 
Share this answer
 
v2
Comments
Member 11653526 13-Apr-16 5:34am    
@Beginner Luck . I don't know actually, I really have minimum experience with java and I write the code from searching google. but it error on me, figures. In c# it worked with no flaws, and i have to convert it to java.
Beginner Luck 13-Apr-16 5:43am    
i cannot see the code changes you make
Member 11653526 13-Apr-16 5:44am    
i haven't do it yet because i realize how do I match it with list<string>?
Beginner Luck 13-Apr-16 21:41pm    
the one you use is not just C# but C# with linq. that why cannot do just that. You have to do the long method. I still not clear is linq support by java. but i just change my answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900