字符串翻转
/*** 翻转字符串2* 传递字符串,返回翻转后的字符串* */public static String stringReverse2(String str){//str转成StringBuilderStringBuilder builder = new StringBuilder(str);builder.reverse();//StringBuilder 的方法翻转字符串return builder.toString();//return new StringBuilder(str).reverse().toString();//一行代码搞定}/*** 翻转字符串1* 传递字符串,返回翻转后的字符串* */public static String stringReverse1(String str){//字符串转数组char[] chars = str.toCharArray();//翻转数组for (int min =0,max=chars.length-1;min<=max;max--,min++){char temp = chars[min];chars[min]=chars[max];chars[max]=temp;}return new String(chars);}
数组可以转成字符串,字符串也能转成数组 (翻转数字)
自定义trim() 去掉字符串两边的空格
" abcd efg " ==>"abcd efg"
public static String myTrim(String str){//去掉字符串开头的空格,方法:替换str = str.replaceFirst(" +", "");//只替换第一个满足要求的//判断字符串是不是以空格结尾while(str.endsWith(" ")){//截取字符串末尾最后一个str = str.substring(0,str.length()-1);//substring:截取字符串的子字符串 [开始,结尾)}return str;}
字符串中的 字符 出现的次数
要求 : 指定字符串 "asdfg3435erAAEExc" , 统计处,小写字母,大写字母,数字,各自出现了多少次,不考虑其它字符.
统计的案例 : 计数器思想 变量++
实现思想 : 字符串换成数组,取出每个元素,分别统计 ASCII码熟悉
/*** 统计字符串中字符和数字出现的次数*/public static void stringCount(String str){if (str == null)return;//定义三个计数器变量int upper = 0 , lower = 0 , number = 0;//字符串转成数组char[] chars = str.toCharArray();for (int i = 0; i < chars.length; i++) {//取出每个元素char ch = chars[i];//判断ch字符的ASCII范围if ( ch >= 'A' && ch <= 'Z')//65--90//大写字母upper ++;else if ( ch >= 'a' && ch <= 'z')//97--122//小写字母lower ++;else if (ch >= '0' && ch <= '9'){//48--57//数字number ++;}}System.out.println("大写字母:"+upper);System.out.println("小写字母:"+lower);System.out.println("数字:"+number);}
字符串出现的次数
字符串A,另一个字符串B,计算B字符串在A字符串中出现几次
例子 : dsabdnabdsnabeabiwpabekabd ab
-
实现过程
-
对字符串进行索引查找 indexOf
-
找到的字符串的索引记录,进行字符串的截取
-
直到找打到未知, indexOf方法是-1
-
一旦找到了,计数器++
-
/*** 字符串出现的次数* @param str 原始字符串* @param sub 要查找的字符串* @return 出现次数*/public static int stringCount(String str, String sub) {if (str == null) {throw new RuntimeException();}//定义变量,计数器int count = 0;//定义变量记录字符串查找后的索引int index = 0;//对字符串出现的位置进行查询//反复查找,使用while循环//循环条件就是indexOf方法返回-1while ((index = str.indexOf(sub)) != -1) {//执行循环index就不等于-1 字符出就出现了count++;//截取字符串的长度,开始索引 index + 被查找的字符串的长度str = str.substring(index + sub.length());}return count;}
哪个字符出现的最多
要求 : 指定字符串自能是(小写)字母 abeegewff , 计算出哪个字符出现的次数最多
限定字符串中字母只能有26个
找每个字符各自出现多少次,找出最大值
-
实现过程 :
-
字符串转成数组 (单个字符操作)
-
创建长度为26的数组,计数器使用
-
取出数组中的字符, (字符-97)对应数组的索引,计数器++
-
找出数组中的最大值
-
/*** 找次数出现最多的字符* @param str 要查找字符串* @return 返回出现次数最多的字符*/public static char charCount(String str) {//字符串转数组char[] chars = str.toCharArray();//定义一个26长度的数组,保存每个字符出现的次数int[] count = new int[26];//遍历数组for (int i = 0; i < chars.length; i++) {//取出单个字符char ch = chars[i];//字符 - 97 作为数组的索引使用(数组,计数器数组)count[ch-97]++;}
// System.out.println(Arrays.toString(count));//取出count数组中最大值的索引int index = 0;//最大值索引int max = count[0];//最大值for (int i : count) {if(max<count[i]){index = i;max = count[i];}}System.out.println(index + " " + max);return (char)(index+97);}