字符串练习
来源:互联网 发布:在线文件管理系统源码 编辑:程序博客网 时间:2024/05/17 05:54
/** * 模拟tirm()方法 去除字符串两段的空格 * * 思路:定义两个变量 start end 分别从字符串的两段对字符串进行逐个字符的判断, * 当出现不是空格的字符时停止判断,整个过程中保持 start <= end * */import com.ivan.util.SystemUtil;public class PractiseOne { public String cutSpace(String str){ //定义前后索引 int start = 0,end = str.length()-1; //从前面对字符串的每个字符进行循环遍历 保持 start <= end while(start <= end && str.charAt(start) == ' '){ start++; } //从后面对字符串的每个字符进行循环遍历i 保存 start <= end while(end >= start && str.charAt(end) == ' '){ end --; } //经过两次遍历后,获得前后不是空格的字符索引, 返回截取字符串的结果 return str.substring(start,end + 1); } public static void main(String[] args) {PractiseOne po = new PractiseOne(); String s = po.cutSpace(" abcdefg ");SystemUtil.sopln(s + ", s.length = " + s.length() );} }
</pre><pre name="code" class="java"><pre name="code" class="java">/** * 判断一个字符串在另一个字符串出现的次数 * * 思路:从一个字符串中查找另一个字符串在本串出现的次数,运用String类中的index重载方法index(String str,int fromIndex)方法对 * 被判断字符串进行遍历,当目标字符串出现一次时,记录出现的位置,第二层判断时,把前一次记录的位置索引加行目标字符串的长度所得数再次串给index方法, * 使其从新位置开始查找,出现一个唱计数器+1一次。 * */import com.ivan.util.SystemUtil;public class PractiseThree { public int appCount(String str,String target){ int count = 0; int index = 0; //运用index重载方法既可以判断目标字符串是否存在,又如果存在就能放回所在位置的索引,方便操作 while((index = str.indexOf(target,index)) != -1){ //改变索引值,从出现目标字符串的位置后面开始查找 index = index + target.length(); //计数器+1count++; } return count; } public static void main(String []args){ int n = new PractiseThree().appCount("aabbkkkk", "kk"); SystemUtil.sop(n); }}
/** * 获取两个字符串中的最大相同子串 * * 思路: * 1.首先,先找出长度比较小的那个字符串。 * 2,然后,定义两个变量,分别记录较小字符串的头和尾。 * 3,对小字符串进行循环,第一次取整个长度,判断在大字符串中是否存在,如果存在,循环结束 * 4,如果不存在,尾部指针 -1(相对与lenth-1),再次判断,若还不存在,头,尾部指针整体后移一位再次判断 * 5,若还是不存在,子尾部指针 -2,再次判断,若不存在,头尾指针整体后移两次(一直移动到小字符串尾部),一直循环 * */import com.ivan.util.SystemUtil;public class PractiseFour {public String getMaxSubString(String s1, String s2){String maxStr = "",minStr = "";//判断字符串的大小maxStr = (s1.length() > s2.length()) ? s1 : s2;minStr = (maxStr == s1) ? s2 : s1;//对小字符串进行循环for(int i = 0;i < minStr.length();i ++){ //前后指针来回移动,取得子串后进行判断是否存在for(int j = 0,z = minStr.length() - i;z < minStr.length()+1;j ++,z ++){String temp = minStr.substring(j, z);if(maxStr.contains(temp)){//返回结果return temp;}}}return "";}public static void main(String []args){SystemUtil.sopln(new PractiseFour().getMaxSubString("asdhellosd", "ahellob"));}}