I'm trying to make some sort of system that would detect java syntax and highlight that code. However, I seem to be having trouble finding a string within a string.
This is what I have so far:
import java.util.Scanner;
public class Client {
private static String[] javaKeywords = {
"abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue",
"default", "do", "double", "else", "enum", "extends", "final", "finnaly", "float", "for", "goto", "if",
"implements", "import", "instanceof", "int", "interface", "long", "native", "new", "package", "primitve",
"private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized",
"this", "throw", "throws", "transient", "try", "void", "volatile", "while"
};
private static String[] javaSyntax = {
"++", "--", "~", "!", "*", "/", "%", "+", "-", " <<", ">>", ">>>", "<", ">", "<=", ">=", "==", "!=", "&",
"^", "|", "&&", "||", "?", ":", "=", "+=", "-=", "/=", "%=", "&=", "^=", "|=", "<<=", ">>=", ">>>="
};
private static Scanner scanner = new Scanner(System.in);
private static StringBuilder builder = new StringBuilder();
public static void main(String args[]) {
String input;
while(!(input = scanner.nextLine()).toLowerCase().contains("exit")) {
switch(input.toLowerCase()) {
case "print":
System.out.println(builder.toString());
continue;
case "clear":
builder = new StringBuilder();
continue;
}
builder.append(input + "\n");
codeWrap(builder.toString());
}
}
private static void codeWrap(String code) {
int A4I = 0, position; // A4I = Account for insert length
for(String keyword: javaKeywords) {
if((position = findInString(code, keyword)) != -1) {
builder.insert(position + A4I, "[code]");
A4I += 6;
builder.insert(position + keyword.length() + A4I, "[/code]");
A4I += 7;
}
}
}
private static int findInString(String string, String keyword) {
for(int index = 0, keywordIndex = 0; index < string.length(); index++) {
keywordIndex = (string.charAt(index) == keyword.charAt(keywordIndex)) ? ++keywordIndex : 0;
if(keywordIndex == keyword.length()) return ((index + 1) - keyword.length());
}
return -1;
}
}
This works for the most part, however if you try to wrap a sentence with two keywords, if keyword b is before keyword a in the javaKeywords array it will return a strange result.
For example: result with a(abstract) before b(while)
abstract while
print
[code]abstract[/code] [code]while[/code]
result with b(while) before a(abstract)
while abstract
print
while [code]a[code]bstra[/code]ct[/code]