基础笔试编程题(jz)
生活随笔
收集整理的這篇文章主要介紹了
基础笔试编程题(jz)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【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總結
以上是生活随笔為你收集整理的基础笔试编程题(jz)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: qq空间域名怎么恢复(qq空间域名怎么恢
- 下一篇: 在eclipse中创建maven项目错误