Problem Statement:
We need to highlight words in a sentence that matches a given list of keywords. Matched words should be surrounded by "[blue]".
Sample Input:
If my code contains many for loops or while loops then my program may run slow.
Keywords List:
if, else, then, until, while, do , for
Sample Output:
[blue]If[blue] my code contains many [blue]for[blue] loops or [blue]while[blue] loops [blue]then[blue] my program may run slow.
Solution: SyntaxHighlighter.java
package com.hellojavatech.syntaxhighlight;
import java.util.ArrayList;
import java.util.Scanner;
public class SyntaxHighlighter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Sentence: ");
String userInput = sc.nextLine();
ArrayList keywords = new ArrayList();
keywords.add("if");
keywords.add("else");
keywords.add("then");
keywords.add("until");
keywords.add("while");
keywords.add("do");
keywords.add("for");
StringBuilder tempString = new StringBuilder();
String[] splitInput = userInput.split(" ");
for (String word : splitInput) {
if(keywords.contains(word)){
tempString.append("[blue]"+word+"[blue]");
}
else{
tempString.append(word);
}
tempString.append(" ");
}
String highlightedString = tempString.toString().trim();
System.out.println("Text after Syntax Highlighting is: ");
System.out.println(highlightedString);
}
}
We need to highlight words in a sentence that matches a given list of keywords. Matched words should be surrounded by "[blue]".
Sample Input:
If my code contains many for loops or while loops then my program may run slow.
Keywords List:
if, else, then, until, while, do , for
Sample Output:
[blue]If[blue] my code contains many [blue]for[blue] loops or [blue]while[blue] loops [blue]then[blue] my program may run slow.
Solution: SyntaxHighlighter.java
package com.hellojavatech.syntaxhighlight;
import java.util.ArrayList;
import java.util.Scanner;
public class SyntaxHighlighter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Sentence: ");
String userInput = sc.nextLine();
ArrayList keywords = new ArrayList();
keywords.add("if");
keywords.add("else");
keywords.add("then");
keywords.add("until");
keywords.add("while");
keywords.add("do");
keywords.add("for");
StringBuilder tempString = new StringBuilder();
String[] splitInput = userInput.split(" ");
for (String word : splitInput) {
if(keywords.contains(word)){
tempString.append("[blue]"+word+"[blue]");
}
else{
tempString.append(word);
}
tempString.append(" ");
}
String highlightedString = tempString.toString().trim();
System.out.println("Text after Syntax Highlighting is: ");
System.out.println(highlightedString);
}
}
No comments:
Post a Comment