package essayExam; /** * 这是我遇到的一些关于String操作的笔试题, * 以下是我按照自己的理解作的解答,欢迎斧正 */ public class StringTest { /** * @param args */ public static void main(String[] args) { String str = "a_b_c_de___f_g_h_i____j_k__l_mn_____xxx"; String resultStr = getRegexStr(str); System.out.println("源字符串:"+str+"/n格式化后的字符串为:"+resultStr); String countStr = "aaabbbbvvvvdddddddd_____ddd"; countStr(countStr); String targetStr = "abc你好啊a!"; String newStr = subByte(targetStr,5); System.out.println(newStr); } // 例题一 // 将一个字符串中的下划线,改成单个下划线,每两个字母之间只能保留一个下划线 // 例如将字符串a_b_c_de___f_g_h_i_______j_k__l_mn修改成a_b_c_d_e_f_g_h_i_j_k_l_m_n // 分析:以“_”为分隔符,将所有有分隔符的串放到一个数组中,对数组中所有的串,去除其剩余的分隔符,然后在循环遍历数组,将每个串后面追加一个“_”字符串(最后一个串后不添加) static String getRegexStr(String str){ if(str==null || "".equals(str)){ return str; } String tempStr; String[] strs = str.split("_"); StringBuffer buf = new StringBuffer(); for(int i=0;i<strs.length;i++){ tempStr = strs[i]; if(tempStr.indexOf("_")!=-1){// 分割串中任然含有待分割字符 tempStr = tempStr.replace("_",""); } if(!("".equals(tempStr))){ if(i!=strs.length-1){ buf.append(tempStr.trim()+"_"); }else{ buf.append(tempStr.trim()); } } } return buf.toString(); } // 例题二 // 统计一个字符串中的每个字符出现的次数,并记录出现最多的一个字符,返回字符+次数 // 分析:首先将所有字符放到一个数组中,然后遍历这个数组,将每个字符与数组比较,记录出现次数,与事先声明的标记值进行比较。 static String countStr(String str){ if(str==null){ return null; } char maxKey = 0; // 标记出现最多的字符 int maxCount = 0; // 标记字符出现的最多次数 System.out.println("源字符串为:"+str); char chars[] = str.toCharArray(); for(int i=0;i<chars.length;i++){ int count = 0; char tempChar = chars[i]; for(int j=0;j<chars.length;j++){ if(tempChar==chars[j]){ count++; } } if(count>maxCount){ maxKey = chars[i]; maxCount=count; } } System.out.println("出现最多的字符:"+maxKey+" , "+maxCount); return maxKey+" , "+maxCount; } // 例题三 // 编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。但是要保证汉字不被截半个, // 如“我 ABC”4,应该截为“我AB”,输入“我 ABC 汉 DEF”,6,应该输出为“我 ABC”而不是“我 ABC+汉的半个”。 // 分析:将字符串转换成字节数组,拷贝出指定字节数的数组。对这个指定字节数的数组进行遍历, // 统计其中含有的Unicode字节的个数,当Unicode字节数能够整除2,则表明所截取的字节数组中,数据是完整的。 static String subByte(String targetStr,int byteCount){ if(targetStr==null){ return null; } byte[] bytes = targetStr.getBytes(); byte[] tem_bytes = new byte[byteCount]; // 指定字节数的byte数组 System.arraycopy(bytes, 0, tem_bytes, 0, byteCount); int tem_bytes_unicode_count = 0; // 标记unicode字节个数 for(int i=0;i<tem_bytes.length;i++){ // 遍历指定字节数的数组 byte temChar = tem_bytes[i]; if(!((temChar>='a' && temChar<='z') || (temChar>='A' && temChar<='Z') || (temChar>=0 && temChar<=9))){ tem_bytes_unicode_count++; // 当字节不为数字或英文字母时,记录下unicode字节个数 } } if(tem_bytes_unicode_count%2==0){ // 所含有的Unicode字符完整(当tem_bytes_unicode_count为0时,不含有Unicode) return new String(bytes,0,byteCount); }else{ return new String(bytes,0,byteCount-1); } } }