简体   繁体   English

如何删除字符串中重复的空格并计算Java中已删除的空格数?

[英]How to remove duplicated white spaces in a string and count the number of removed spaces in Java?

This forum has a solution for removing duplicated white spaces in java using 该论坛提供了使用以下方法删除Java中重复的空格的解决方案

String.replaceAll() 

However this solution can't be applied if we need to count the removed white spaces. 但是,如果我们需要计算已删除的空白,则无法应用此解决方案。 Is there any other way to solve this problem? 还有其他解决方法吗?

您之前replaceAll()你可以遍历所有的字符stringVar.toCharArray()和计数。

Why not? 为什么不?

 String s = "     ";
 String whiteSpaceLess = s.replaceAll("  ", "");
 int diff = s.length() - whiteSpaceLess.length();

Simply retain the original string in another variable. 只需将原始字符串保留在另一个变量中即可。 After trimming it from extra spaces, just calculate the length difference: this is the number of spaces removed. 从多余的空格中修剪后,只需计算长度差即可:这是删除的空格数。

If you have a String s, 如果您有String,

String t = s.replaceAll("\\s+", " ");
System.out.println(t);
int count = s.length() - t.length();
System.out.println(count);

You can remove the whitespaces using replaceAll, and count the difference in length between the strings to get the number of removed spaces. 您可以使用replaceAll删除空格,并计算字符串之间的长度差,以获取删除的空格数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM