Java 去除文本文件多余的空格字符串
/** * 移除多余空行和空格 */ 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++; } else { blankCount = 0; resultSB.append(dealSpace4OneLine(line)); } } 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++; } else { spaceCount = 0; sb.append(curChar); } } return sb.toString(); }
有什么不同见解可以在评论区共同讨论
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!