Blame |
Last modification |
View Log
| RSS feed
package com.gebauz.bauzoid.parser;
public class Preprocessor
{
// Constants========================================================================================
// Embedded Types===================================================================================
// Members==========================================================================================
// Methods==========================================================================================
public static String stripComments
(String str
)
{
return stripComments
(str,
"//",
"/*",
"*/");
}
public static String stripComments
(String str,
String lineCommentBegin,
String commentBegin,
String commentEnd
)
{
String result =
"";
int pos =
0;
while (pos
< str.
length())
{
if (!lineCommentBegin.
isEmpty() && isNextString
(str, pos, lineCommentBegin
))
{
// skip until end of line
while ((pos
< str.
length()) && (!isNextString
(str, pos,
"\n")))
{
pos++
;
}
}
else if (!commentBegin.
isEmpty() && !commentEnd.
isEmpty() && isNextString
(str, pos, commentBegin
))
{
// skip until commentEnd encountered
while (pos
< str.
length())
{
if (isNextString
(str, pos, commentEnd
))
{
// skip over commentEnd and then exit loop
pos += commentEnd.
length();
break;
}
pos++
;
}
}
result = result + str.
charAt(pos
);
pos++
;
}
return result
;
}
public static boolean isNextString
(String str,
int pos,
String substr
)
{
for (int i =
0; i
< substr.
length(); i++
)
{
if ((pos + i
) >= str.
length())
return false;
if (substr.
charAt(i
) != str.
charAt(pos + i
))
return false;
}
return true;
}
/** Trim whitespaces from the begin and end of the string. */
public static String trim
(String str,
char[] whitespaces
)
{
int begin =
0;
int end = str.
length()-
1;
while (begin
< str.
length())
{
for (char c : whitespaces
)
{
if (str.
charAt(begin
) == c
)
{
begin++
;
continue;
}
}
// no whitespace -> break;
break;
}
while (end
>=
0)
{
for (char c : whitespaces
)
{
if (str.
charAt(end
) == c
)
{
end--
;
continue;
}
}
// no whitespace -> break;
end++
;
break;
}
if (begin
>= end
)
return "";
return str.
substring(begin, end
);
}
public static String escapeString
(String src
)
{
StringBuilder result =
new StringBuilder();
int i =
0;
while (i
< src.
length())
{
char c = src.
charAt(i
);
i++
;
if (c ==
'\\')
{
// ecape character
char next = src.
charAt(i
);
i++
;
switch(next
)
{
case '\\':
// escaped backslash
result.
append('\\');
break;
case 'u':
// escape Unicode character
String codeStr = src.
substring(i, i+
4);
i +=
4;
Integer code =
Integer.
decode("0x" + codeStr
);
result.
append(Character.
toChars(code
));
break;
case 'n':
result.
append('\n');
break;
}
}
else
{
result.
append(c
);
}
}
return result.
toString();
}
// Getters/Setters==================================================================================
}