Reputation: 21
For example, I have a string variable line
(line.contains("for") || line.contains("def") || line.contains("if") || line.contains("while") || line.contains("else") || line.contains("elif")
and I want to set a new string variable keyword to the keyword in this conditional statement, how would be able to do this, like keyword = keyword in line.
Upvotes: 2
Views: 114
Reputation: 2436
alternative here:
List<String> keywords = new LinkedList<String>;
keywords.add("for"); // put your keywords in a list
keywords.add("def");
keywords.add("if");
keywords.add("else");
String strword;
for(keyword:keywords){
if(line.contains(keyword)){
String strword = keyword;
}
}
Upvotes: 0
Reputation: 5394
Stream provide a simple and elegant solution in this case:
String keyword = Stream.of("elif", "for", "def", "if", "while", "else")
.filter(line::contains)
.findFirst()
.orElse("no-keyword-found");
Note: "elif" must be placed before "if"
Upvotes: 4
Reputation: 44110
Why not something like this?
public static Optional<String> getFirstMatch(String string, String... subStrings)
{
return Arrays.stream(subStrings).filter(string::contains).findFirst();
}
Sample usage:
Optional<String> match = getFirstMatch("myInput", "my", "Input");
if (match.isPresent())
{
String foo = match.get();
//...
}
Upvotes: 0