/**
* 重复某个字符
*
* 例如:
* 'a' 5 => "aaaaa"
* 'a' -1 => ""
*
* @param c 被重复的字符
* @param count 重复的数目,如果小于等于0则返回""
* @return 重复字符字符串
*/
public static String repeat(char c, int count) {
if (count < 0){
return "";
}
char[] a = new char[count];
for(int i=0; i<count; i++){
a[i] = c;
}
String str = new String(a);
return str;
}
/**
* 将已有字符串填充为规定长度,如果已有字符串超过这个长度则返回这个字符串
* 字符填充于字符串前
*
* 例如:
* "abc" 'A' 5 => "AAabc"
* "abc" 'A' 3 => "abc"
*
* @param str 被填充的字符串
* @param filledChar 填充的字符
* @param len 填充长度
* @return 填充后的字符串
*/
public static String fillBefore(String str, char filledChar, int len){
if (str == null){
return "";
}
int newLen = str.length();
if(len <= newLen){
return str;
}else{
str = repeat(filledChar, len-newLen)+str;
}
return str;
}
/**
* 移除字符串中所有给定字符串
* 例:removeAll("aa-bb-cc-dd", "-") => aabbccdd
*
* @param str 字符串
* @param strToRemove 被移除的字符串
* @return 移除后的字符串
*/
public static String removeAll(CharSequence str, CharSequence strToRemove){
if(str == null){
return"";
}
String str1 = new String(str.toString());
String remove = new String(strToRemove.toString());
return str1.replaceAll(remove,"");
}
/**
* 反转字符串
* 例如:abcd => dcba
*
* @param str 被反转的字符串
* @return 反转后的字符串
*/
public static String reverse(String str){
if(str == null){
return "";
}
if(str.length() == 0 || str.length() == 1){
return str;
}
char[] arr = str.toCharArray();
for(int i=0; i<str.length()/2; i++){
char temp = arr[i];
arr[i] = arr[str.length()-1-i];
arr[str.length()-1-i] = temp;
}
str = new String(arr);
return str;
}
//测试
public static void main(String[] args){
String str1 = null;
String str2 = repeat('l', 5);
String str3 = "he.ll.ow.or.d";
String str4 = "l";
//repeat
System.out.println("实现后字符串为:"+str2);
//fillBefore
System.out.println("填充的字符串为:"+fillBefore(str1, 'L',18));
System.out.println("填充的字符串为:"+fillBefore(str3, 'L',18));
System.out.println("填充的字符串为:"+fillBefore(str3, 'L',5));
//removeAll
System.out.println("移除后的字符串为:"+removeAll(str1,"."));
System.out.println("移除后的字符串为:"+removeAll(str3,"."));
//reverse
System.out.println("反转后的字符串为:"+reverse(str1));
System.out.println("反转后的字符串为:"+reverse(str3));
System.out.println("反转后的字符串为:"+reverse(str4));
}