字符串的操作 实现 重复 前置 后置的添加 还有 逆置 移除等

 











1
public class Strings { 2 3 4 /** 5 * 重复某个字符 6 * <p> 7 * 例如: 8 * 'a' 5 => "aaaaa" 9 * 'a' -1 => "" 10 * 11 * @param c 被重复的字符 12 * @param count 重复的数目,如果小于等于0则返回"" 13 * @return 重复字符字符串 14 */ 15 public static String repeat(char c, int count) { 16 char[] a = new char[count]; 17 if (count > 0) { 18 for (int i = 0; i < count; i++) { 19 a[i] = c; 20 } 21 } 22 else 23 return null; 24 } 25 String str1 = new String(a); //强转 26 return str1; 27 28 29 } 30 public static String fillafter(String str, char filledChar, int len) { 31 char []charArray = str.toCharArray(); // 利用 toCharArray 方法将STR 字符转换为 字符数组 用char [] ___ (数组名接受) 32 char[]arr=new char[len]; 33 if(len<charArray.length){ 34 return str; 35 } 36 else{ 37 for(int i= 0;i<charArray.length;i++){ 38 arr[i]=charArray[i]; 39 40 } 41 for(int i=charArray.length;i<len;i++){ 42 arr[i]= filledChar; 43 } 44 String Str3 = new String(arr); //强转一定要注意符号的书写; 45 return Str3; 46 47 48 } 49 50 } 51 // 实现在字符串的前面加上字符操作,重点在于对于字符串的的长度在FOR循环里面的掌握 52 53 public static String fillBefore(String str, char filledChar, int len) { 54 char []charArray1 = str.toCharArray(); 55 char []array=new char [len]; 56 if(len<charArray1.length){ 57 return str; 58 } 59 else{ 60 61 for(int j = 0, i = len-charArray1.length;i<len;i++,j++){ 62 array[i]=charArray1[j]; 63 } 64 for(int i = 0;i<len-charArray1.length;i++){ 65 array[i]= filledChar; 66 } 67 String Str7 = new String(array); 68 return Str7; 69 } 70 71 72 73 74 } 75 /** 76 * 移除字符串中所有给定字符串 77 * 例:removeAll("aa-bb-cc-dd", "-") => aabbccdd 78 * 79 * @param str 字符串 80 * @param strToRemove 被移除的字符串 81 * @return 移除后的字符串 82 */ 83 public static String removeAll(CharSequence str, CharSequence strToRemove) { 84 String Str4= str.toString(); 85 String Str5= strToRemove.toString(); 86 char []arr1 = Str4.toCharArray(); 87 char []arr2 = Str5.toCharArray(); 88 String a =""; 89 for(int i =0;i<arr1.length;i++){ 90 if(arr1[i]!=arr2[0]){ 91 a=a+arr1[i]; 92 93 } 94 } 95 return a; 96 97 } 98 // 用第三个元素交换首尾的字符 left ++ right -- 这样就能使得 字符的逆置 99 public static String reverse(String str){ 100 char [] arra=str.toCharArray(); 101 char [] a = new char [arra.length]; 102 int left = 0; 103 int right = arra.length-1; 104 char tmp = '0'; 105 while(left<right){ 106 tmp = arra[left]; 107 arra[left]=arra[right]; 108 arra[right]= tmp; 109 left++; 110 right--; 111 112 } 113 String Str6 = new String(arra); //强制转换为String类型 114 return Str6; 115 116 } 117 118 119 public static void main(String[] args) { 120 char a = 'a'; 121 int count = 5; 122 char b = 'A'; 123 System.out.println(reverse("abcdef")); 124 System.out.println(removeAll("aa-bb-cc","-")); 125 System.out.println(repeat(a,count)); 126 System.out.println(fillafter("ABCD", b, 6)); 127 System.out.println(fillBefore("ABCD", b, 6)); 128 129 130 } 131 }

 

posted on 2018-11-26 19:20  singleday  阅读(210)  评论(0编辑  收藏  举报