1.字符的尾部填充
public class Test17{
public static void main(String[] args){
System.out.println(fillBefore("avsg",'t',8));
}
public static String fillBefore(String str, char filledChar, int len) {
if(str.length() >= len){
return str;
}
else{
StringBuffer sb = new StringBuffer(str);
for(int i = sb.length();i < len;i++){
sb.insert(sb.length(),filledChar);
}
return sb.toString();
}
}
}
2.字符的首部填充,只需改填充的位置即可
public class Test17{
public static void main(String[] args){
System.out.println(fillBefore("avsg",'t',8));
}
public static String fillBefore(String str, char filledChar, int len) {
if(str.length() >= len){
return str;
}
else{
StringBuffer sb = new StringBuffer(str);
for(int i = sb.length();i < len;i++){
sb.insert(sb.0,filledChar);
}
return sb.toString();
}
}
}
3移除字符串中所有给定字符串
public class removeAll{
public static void main(String[] args){
remove();
}
static void remove(){
String str =" hello,world" ;
System.out.println("移除前的字符串为"+str);
System.out.println("移除指定的字母0");
System.out.println("移除l后的字符串为:");
String str1=str.replaceAll("0", "");//将l移除,其实替换,不过替换的内容为空,如果将引号中给一个内容,就会替换
System.out.println("["+str1.trim()+"]");//将str两边的空格删掉
//我们再次移除一个字母d
System.out.println("移除一个字母d后的字符串为:");
String str2=str1.replaceAll("d","");
System.out.println(str2);
//再将o字母替换为i like you
System.out.println("替换后的字符串为:");
String str3 =str2.replaceAll("o","i like you");
System.out.println(str3);
}
}
4.String类扩展功能实现
public class Test15{
public static void main(String[] args){
// char[] data ={'a'};
//for(int i =0;data.length<6;++i){
// data[i]=data[1];
//}
//System.out.println(data);
System.out.println(repeat('q',7));
}
public static String repeat(char c,int count){
if(count <= 0){
return "";
}
char [] data;
data = new char [count];
for(int i = 0;i < count;i++){
data[i] = c;
}
return (new String(data));
}
}
5反转字符串
public class Reverse{
public static void main(String[] args){
reverse();
}
static void reverse(){
String str = "i am winner";
System.out.println("反转前的字符串为"+str);
//StringBuffer str1 = new StringBuffer(str);
System.out.println("反转之后的字符串为");
StringBuffer str1 = new StringBuffer(str);
System.out.println(str1.reverse());
String str2 =str.replaceAll(" ","");//把里面的空格去掉;
System.out.println("去掉空格的str 为:");
System.out.println(str2);
System.out.println("反转之后str2为:");
StringBuffer str3 =new StringBuffer(str2);
System.out.println(str3.reverse());
}
}