【1】计算某个单词在某文件中出现的次数.
// 计算某个单词在某文件中出现的次数.
public class WordCounter {private static int counter;private static String path = System.getProperty("user.dir")+ File.separator + "src" + File.separator + "com" + File.separator+ "interview" + File.separator;public static void main(String[] args) throws IOException {func(path + "hello.txt", "hello");}static void func(String filename, String word) throws IOException {BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));String line;while ((line = br.readLine()) != null) {System.out.println(line);for (int i = 0; i <= line.length() - word.length();) {if (word.equals(line.substring(i, i + word.length()))) {i += word.length();counter++;}else i++;}System.out.println(counter);}System.out.println(word+"在文件里出现的次数 counter = "+ counter);}
}
hello, my name is hello // hello.txt
where are you. hello. yoyoyo.
hellohello
hello, my name is hello // result output.
2
where are you. hello. yoyoyo.
3
hellohello
5
hello在文件里出现的次数 counter = 5
【2】对字符串进行处理.(只包括小写字母 数字 空格)
// 对字符串进行处理.(只包括小写字母 数字 空格)
// 将多个空格转为一个空格.
// 在字符和数字之间插入下划线.
// 单词首字母要大写.
public class StringProcessed {public static void main(String[] args) {String str = "hello my name is tang222tang232tang2rong where are you2now here";System.out.println(func(str));}static String func(String str) {str = " " + str;char[] array = str.toCharArray();StringBuilder sb = new StringBuilder();for (int i = 0; i < array.length; i++) {// if(array[i] == ' ') continue; // 字符是空格,continue. // 不要这一行,减少圈复杂度(idea from huawei.)if(array[i] >='a' && array[i] <='z' ) { // 字符是字母.if(array[i-1] == ' ') { // 单词首字母大写.sb.append(" ");sb.append((char)(array[i]-32));continue;} sb.append(array[i]);} else if(array[i]>='0' && array[i]<='9') { // 字符是数字.if(array[i-1]>='a' && array[i-1]<='z' ||array[i-1]>='A' && array[i-1]<='Z') { // 前一个字符是字母,则加下划线.sb.append("_");}sb.append(array[i]);}}return sb.substring(1, sb.length());}
}
//output:
Hello My Name Is Tang_222tang_232tang_2rong Where Are You_2now Here