String自定义方法
/** *找出字符串中有几个特定的字符串 * @param souce 源字符串 * @param find 指定需要查询计数字符串 * @return 返回指定字符串的技术值 */ public int getStrCount(String souce, String find) { int count = 0; int index = 0; while (true) { index = souce.indexOf(find, index); if (index > 0) { count++; index++; } else { break; } } return count; }
public static void main(String[] args) { String str = "aaabbbabbabc"; String find = "ab"; System.out.println(getStrCount(str, find)); }
/** *相当于String的replaceAll()方法 * @param source 源字符串 * @param find 需要被代替的子字符串 * @param replacement 代替字符串 * @return 被替换后的字符串 */ public static String replaceAll(String source, String find, String replacement) { StringBuffer buffer = new StringBuffer(); while (source.indexOf(find) != -1) { int index = source.indexOf(find); buffer.append(source.substring(0, index)); buffer.append(replacement); source = source.substring(index + find.length()); } buffer.append(source); return buffer.toString(); }
public static void main(String[] args) { String str = "aaaasdxffffwweds"; System.out.println(replaceAll(str, "aa", "bb")); }
/**字符串的replace(char oldChar, char newChar) * @param source 原字符串 * @param find 查找的字符 * @param replacewith 替代原有的字符 */ public static String replace(String source, char find, char replacewith){ StringBuffer buffer=new StringBuffer(); while(source.indexOf(find)!=-1){ int index=source.indexOf(find); buffer.append(source.substring(0,index)); buffer.append(replacewith); source=source.substring(index+1); } buffer.append(source); return buffer.toString(); }
public static void main(String[] args) { String str = "aaaasdxffffaaaaeds"; System.out.println(str.replace(‘a‘, ‘b‘)); }
//将通过分隔符分割字符串,分隔符是分割字符串的每个字符 public static String[] splitChar(String str,String stSplit) { ArrayList<String> lst = new ArrayList<String>(); StringTokenizer st = new StringTokenizer(str,stSplit); while(st.hasMoreTokens()) { lst.add(st.nextToken()); } return (String[])lst.toArray(new String[st.countTokens()]); }