题目
写函数makeUpperCase。
测试用例:
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
public class SolutionTest {
Upper u = new Upper();
@Test
public void testSomething() {
assertEquals("HELLO",u.MakeUpperCase("hello"));
assertEquals("HELLO WORLD",u.MakeUpperCase("hello world"));
}
}
解题
My
class Upper{
public static String MakeUpperCase(String str){
char[] arr = str.toCharArray();
for (int i = 0; i< arr.length; i++) {
if (arr[i]<=122 && arr[i]>=97) {
arr[i] -= 32;
}
}
return new String(arr);
}
}
Other
class Upper{
public static String MakeUpperCase(String str){
return str.toUpperCase();
}
}
import java.nio.charset.StandardCharsets;
class Upper{
public static String MakeUpperCase(String str){
byte[] bytes = null;
bytes = str.getBytes(StandardCharsets.US_ASCII);
// a - 97, z - 122
// A - 65, Z - 90
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
if (b > (byte) 'a' && b < (byte) 'z') {
bytes[i] = (byte) (b - 32);
}
}
return new String(bytes, StandardCharsets.US_ASCII);
}
}
后记
库函数toUpperCase()一句话可以搞定的事,为啥还要特地封装成另一个函数呢,我思考了一下,自己写了一个简单的实现。