org.joinedworkz.common.helper.StringHelper.xtend Maven / Gradle / Ivy
package org.joinedworkz.common.helper
import javax.inject.Singleton
@Singleton
class StringHelper {
public static final char NL = '\n'
public static final char CR = '\r'
def boolean isNewLineChar(char c) {
return c == NL || c == CR
}
def boolean beginsLineChar(StringBuilder buffer) {
return buffer.length == 0 || isNewLineChar(buffer.charAt(buffer.length - 1))
}
def trimLastLineBreak(String str) {
if (str !== null) {
var totalCount = 0
var crCount = 0
var nlCount = 0
for (var i = str.length - 1; i >= 0; i--) {
totalCount++
val c = str.charAt(i)
if (c == CR) {
crCount++
}
if (c == NL) {
nlCount++
}
if (totalCount > crCount + nlCount) {
if (totalCount == 1) {
return str
} else {
return str.substring(0, str.length - totalCount + 1)
}
}
}
}
}
def String contentOfLineBefore(String str, int index) {
for (var i = index; i >= 0; i--) {
val c = str.charAt(i)
if (c == CR || c == NL) {
return str.substring(i + 1, index);
}
}
return str
}
def String contentOfLineAfter(String str, int index) {
val strLength = str.length
for (var i = index; i < strLength; i++) {
val c = str.charAt(i)
if (c == CR || c == NL) {
return str.substring(index, i);
}
}
return str.substring(index)
}
def boolean containsLineBreak(String str) {
if (str !== null) {
return str.indexOf(CR) >= 0 || str.indexOf(NL) >= 0
} else {
return false
}
}
def insertLinesOfString(StringBuilder buffer, String str, String indention) {
val hasContent = str.trim.length > 0
if (!hasContent) {
return
}
val lines = str.split("\\r?\\n")
val lastChar = str.charAt(str.length - 1)
val hasIndention = indention.length > 0
val int lineCount = lines.length
val int lastLine = lineCount - 1
for (var int i = 0; i < lineCount; i++) {
val line = lines.get(i)
if (hasIndention && beginsLineChar(buffer)) {
buffer.append(indention)
}
buffer.append(line)
if (i < lastLine || isNewLineChar(lastChar)) {
buffer.append("\r\n")
}
}
}
}