最近在開發一個小型的圈子系統。功能相似一個簡化的微博。用戶能夠在圈子裏發帖子,回覆帖子,點贊等等。項目上線不久就發現有不少用戶在圈子裏發廣告,手段之豐富使人歎爲觀止啊。產品大哥昨天忽然跑過來跟我說:如今圈子裏有不少廣告,並且發廣告的人爲了吸引別人的注意力常常會發出不少帶有不少空行和空格的帖子跟回覆。這樣一個帖子就會沾滿屏幕,十分影響使用。產品大哥要求我當即開發一套過濾邏輯,刪除多餘的空格和帖子。正則表達式
按照以下要求處理字符串app
/** * 移除多餘空行和空格 */ public static String dealRedundantSpaceAndBlankLine(String content) { if (content == null || content.length() == 0) { return ""; } StringBuilder strAfterRemoveCRSB = new StringBuilder(); for (int i = 0; i < content.length(); i++) { if (content.charAt(i) != '\r') strAfterRemoveCRSB.append(content.charAt(i)); } String strAfterRemoveCR = strAfterRemoveCRSB.toString(); if (strAfterRemoveCR == null || strAfterRemoveCR.length() == 0) { return ""; } StringBuilder resultSB = new StringBuilder(); String[] lines = strAfterRemoveCR.split("\n"); int blankCount = 0; for (String line : lines) { if (line == null) { continue; } String lineTrim = line.trim(); if ("".equals(lineTrim)) { blankCount++; if (blankCount <= 2) { resultSB.append("\n"); } } else { blankCount = 0; resultSB.append(dealSpace4OneLine(line)).append("\n"); } } resultSB.deleteCharAt(resultSB.length() - 1); return resultSB.toString(); } /** * 移除1行中的多餘空格 */ public static String dealSpace4OneLine(String line) { if (line == null || "".equals(line)) { return ""; } int spaceCount = 0; StringBuilder sb = new StringBuilder(); for (int i = 0; i < line.length(); i++) { char curChar = line.charAt(i); if (curChar == ' ') { spaceCount++; if (spaceCount <= 5) { sb.append(' '); } } else { spaceCount = 0; sb.append(curChar); } } return sb.toString(); } public static void main(String[] args) { String str = "呵呵 測試\n\n\n\n \n \r\n將風控打掃房 間\n\n\n\n \n \n 快遞費解封時代峯峻\n\r\n 發的幾點睡 "; String result = dealRedundantSpaceAndBlankLine(str); System.out.println(result); }