java 计算字符串标记时忽略空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10166767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ignoring spaces while counting String tokens
提问by Speakr
I am working on a homework assignment for a class and I have solved almost all of it, but am struggling with one part.
我正在为一个班级做家庭作业,我已经解决了几乎所有的问题,但有一个部分正在挣扎。
For the assignment, we are supposed to write a program that will count the frequency of occurrence of letters in any given string and then print out a map of them to the console. I have written the program and it works almost correctly, but I cannot get the map to ignore whitespace. It seems to find two different kinds of whitespace as well, one that is the space between words and another that I cannot figure out.
对于作业,我们应该编写一个程序来计算任何给定字符串中字母的出现频率,然后将它们的映射打印到控制台。我已经编写了程序并且它几乎可以正常工作,但是我无法让地图忽略空格。它似乎也找到了两种不同的空格,一种是单词之间的空格,另一种是我无法弄清楚的。
I've tried myString.replaceAll(" ", "");
and myString.trim();
to try and eliminate the whitespace before counting the frequency of letters, but it still counts both types of whitespace each time.
我已经尝试myString.replaceAll(" ", "");
并myString.trim();
尝试在计算字母频率之前消除空格,但它每次仍然计算两种类型的空格。
Any insight or help is appreciated. I could turn it in like this, but I don't like half-assing projects. Here is the code:
任何见解或帮助表示赞赏。我可以像这样上交,但我不喜欢半途而废的项目。这是代码:
import java.util.*;
public class LetterFrequency {
public static void main( String[] args ) {
Map< String, Integer > myMap = new HashMap< String, Integer >();
createMap( myMap );
displayMap( myMap );
}
private static void createMap( Map< String, Integer > map ) {
Scanner scanner = new Scanner( System.in );
System.out.println( "Enter a string:" );
String input = scanner.nextLine();
System.out.println("String: "+input);
String[] tokens = input.split("");
for ( String token : tokens ) {
String letter = token.toLowerCase();
if ( map.containsKey( letter ) ) {
int count = map.get( letter );
map.put( letter, count + 1 );
}
else
map.put( letter, 1 );
}
}
private static void displayMap( Map< String, Integer > map ) {
Set< String > keys = map.keySet();
TreeSet< String > sortedKeys = new TreeSet< String >( keys );
System.out.println( "\nMap contains:\nKey\t\tValue" );
for ( String key : sortedKeys )
System.out.printf( "%-10s%10s\n", key, map.get( key ) );
System.out.printf(
"\nsize: %d\nisEmpty: %b\n", map.size(), map.isEmpty() );
}
}
回答by K Mehta
String.replaceAll
should work. Keep in mind that String.replaceAll
returns a String
. So you have to use the string it returns to perform the rest of your computation.
String.replaceAll
应该管用。请记住,String.replaceAll
返回一个String
. 因此,您必须使用它返回的字符串来执行其余的计算。
For instance, if you have:
例如,如果您有:
String myString = "hello world";
myString.replaceAll(" ", "");
myString
will still be "hello world"
myString
仍将是“你好世界”
You'd want:
你会想要:
String myNewString = myString.replaceAll(" ", "");
After which myNewString
will have no spaces.
之后myNewString
将没有空格。
Also, you can simplify your character iteration by using
此外,您可以通过使用简化您的字符迭代
for (int i = 0; i < input.length(); i++){
char letter = input.charAt(i);
This will fix your additional "whitespace being counted" problem. This is because when you call myString.split("")
, the first element in the returned list is "" (an empty string).
这将解决您额外的“计算空白”问题。这是因为当您调用 时myString.split("")
,返回列表中的第一个元素是 ""(空字符串)。
回答by Tim Pote
You can try myString.split("\\s+");
to get rid of all whitespace and split at the same time.
您可以尝试myString.split("\\s+");
去除所有空格并同时拆分。
As @Kshitij Mehta pointed out, make sure you use the return value of that method. So your code would look like this:
正如@Kshitij Mehta 指出的那样,请确保使用该方法的返回值。所以你的代码看起来像这样:
String input = scanner.nextLine();
System.out.println("String: "+input);
input = input.trim();
String[] tokens = input.split("\s+");
回答by Péter T?r?k
Alternative to String.replaceAll
: You can filter your inputto ignore any non-alphabetic characters before counting them (or filter your map similarly before printing the result). E.g.
替代方法String.replaceAll
:您可以过滤您的输入以在计算它们之前忽略任何非字母字符(或在打印结果之前类似地过滤您的地图)。例如
for ( String token : tokens ) {
if (Character.isLetter(token)) {
String letter = token.toLowerCase();
...
}
}
回答by Laky
Alternatively, you can use Character.isLetter(char c)method to determine whether a character is really a letter.
或者,您可以使用Character.isLetter(char c)方法来确定字符是否真的是字母。
回答by endqwerty
@Kshitij Mehta is correct.
@Kshitij Mehta 是正确的。
Your problem is a combination of not removing whitespace by setting
您的问题是不通过设置删除空格的组合
input = input.replace(" ", "");
Also, your second problem was using Strings
instead of char
(and Character for your maps) to save the letters(which are characters). It was just the unexpected use of String for char that made java perform unexpectedly.
此外,您的第二个问题是使用Strings
而不是char
(以及您的地图的字符)来保存字母(字符)。只是意外地将 String 用于 char 使 java 执行意外。
回答by Maruf Islam Joy
import java.util.*;
public class M {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
s.toCharArray();
String n = s.replaceAll(" ","");
System.out.println(n.length());
}
}
You can try this. I know you already did it. But I think it will help someone else.
你可以试试这个。我知道你已经做到了。但我认为这会帮助别人。