2

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.

4
  • 2
    @pmcarpan i dont think it is a duplicate, he is asking after the condition he wants to assign to variable that makes true the condition Commented Oct 2, 2018 at 12:48
  • line.contains("if") || line.contains("elif") is redundant; if the line does not contain "if", then it won't contain "elif". Commented Oct 2, 2018 at 12:50
  • @Liamnator why dont you put the keywords in a List. Commented Oct 2, 2018 at 12:52
  • For the record: if you really try to parse some sort of language, then contains() is wrong. Then you have to use a parser, to correctly identify and process the different elements of your input. What if the line is if a == "def"or something like that? Commented Oct 2, 2018 at 12:57

3 Answers 3

4

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"

Sign up to request clarification or add additional context in comments.

1 Comment

"I removed "elif" keyword because it will never be returned." → It will, as long as it comes before if.
0

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();
    //...
}

Comments

0

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;
 }    
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.