题目
这很简单。您的目标是创建一个删除字符串的第一个和最后一个字符的函数。你有一个参数,原始字符串。您不必担心少于两个字符的字符串。
测试用例:
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class RemoveCharsTest {
@Test
public void testRemoval() {
assertEquals("loquen", RemoveChars.remove("eloquent"));
assertEquals("ountr", RemoveChars.remove("country"));
assertEquals("erso", RemoveChars.remove("person"));
assertEquals("lac", RemoveChars.remove("place"));
}
}
解题
My
public class RemoveChars {
public static String remove(String str) {
return str.substring(1,str.length()-1);
}
}
Other
大部分人和我的答案一样。也有个别用正则表达式的。
public class RemoveChars {
public static String remove(String str) {
return str.replaceAll("^.|.$", "");
}
}
后记
有人提到了这个String要用final来修饰,如下
public static String remove(final String text) {
return text.substring(1, text.length() - 1);
}
理由是
Final is class and hence object of String, but not reference to this object.
example:
String foo = "foo";
String bar = "bar";
foo = bar;
System.out.println(foo); // bar
And it's a good practice to make method arguments final because it increase code readability.
网友评论