1. 自己写trim方法
public class Demo3 { public static void main(String[] args) { System.out.println(myTrim(" 123 ")); } //需求:去除字符串两边空格的函数 public static String myTrim(String str){ int start = 0; int end = str.length()-1; //去掉前面的空格 for (int i = 0; i < str.length()-1; i++) { char ch = str.charAt(start); if(ch == ' '){ start++; }else{ break; } } //去掉后面的空格 for (int i = end; i >0; i--) { char ch = str.charAt(i); if(ch == ' '){ end--; }else{ break; } } //截取字符串(因为不包含最后一位数,所以加1) return str.substring(start,end+1); } }
2.获取上传文件名 "D:\20120512\day12\Demo1.java"
public class Demo4 { public static void main(String[] args) { System.out.println(getFilename("D:\20120512\day12\Demo1.java")); } //需求:获取上传文件名 "D:\20120512\day12\Demo1.java" public static String getFilename(String path){ //根据获取最后一个的索引+1 int start = path.lastIndexOf('\')+1; return path.substring(start); } }
3.将字符串对象中存储的字符反序
public class Demo5 { public static void main(String[] args) { System.out.println(reaverseString("hello")); } //需求:将字符串对象中存储的字符反序 public static String reaverseString(String str){ char[] ch = str.toCharArray(); for (int start = 0,end = ch.length-1; start < end; start++,end--) { char temp = ch[start]; ch[start] = ch[end]; ch[end] = temp; } return new String(ch); } }
4. 求一个子串在整串中出现的次数
public class Demo6 { public static void main(String[] args) { System.out.println(getCount("abcabcjgejgabc","abc")); } //求一个子串在整串中出现的次数 public static int getCount( String src , String tag ){ // 0. 定义索引变量和统计个数的变量 int index = 0; int count = 0; // 1. 写循环判断 while ( ( index = src.indexOf(tag) ) != -1 ){ src = src.substring( index + tag.length() ); // index 4 + 4 = 8 count++; } return count; } }