Last active
August 29, 2015 14:19
-
-
Save marciojrtorres/f90c8daf5173f603ecfd to your computer and use it in GitHub Desktop.
Prova DBO-2015 1ro Bim Questão #1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class StringUtil { | |
public static String trimLeft(String string) { | |
char[] chars = string.toCharArray(); | |
int i = 0; | |
for (; i < chars.length; i++) if (chars[i] != ' ') break; | |
return new String(subArray(chars, i, chars.length)); | |
} | |
public static String trimRight(String string) { | |
char[] chars = string.toCharArray(); | |
int i = chars.length - 1; | |
for (; i > 0; i--) | |
if (chars[i] != ' ') | |
break; | |
return new String(subArray(chars, 0, i + 1)); | |
} | |
public static String trim(String string) { | |
return trimLeft(trimRight(string)); | |
} | |
public static boolean eq(String string1, String string2) { | |
char[] chars1 = string1.toCharArray(); | |
char[] chars2 = string2.toCharArray(); | |
if (chars1.length != chars2.length) return false; | |
for (int i = 0; i < chars1.length; i++) | |
if (chars1[i] != chars2[i]) | |
return false; | |
return true; | |
} | |
private static char[] subArray(char[] array, int start, int end) { | |
char[] narray = new char[end - start]; | |
for (int i = start; i < end; i++) | |
narray[i - start] = array[start + (i - start)]; | |
return narray; | |
} | |
public static void main(String[] args) { | |
// Aparar String à esquerda: remover espaços à esquerda da String | |
System.out.println(eq(trimLeft(" abc "), "abc ")); | |
System.out.println(eq(trimLeft(" "), "")); | |
System.out.println(trimLeft(" A ").toCharArray().length == 2); | |
System.out.println(eq(trimLeft("left"), "left")); | |
// Aparar String à direita: remover espaços à direita da String | |
System.out.println(eq(trimRight(" abc "), " abc")); | |
System.out.println(eq(trimRight(" "), "")); | |
System.out.println(eq(trimRight("right"), "right")); | |
// Aparar String em ambos lados | |
System.out.println(eq(trim(" abc "), "abc")); | |
System.out.println(eq(trimRight("both"), "both")); | |
System.out.println(eq(trimRight(" bo th "), "bo th")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment