简体   繁体   English

为什么我的Java StringTokenizer读取空白?

[英]Why does my Java StringTokenizer read emptyspace?

I wrote this program that should only break down the string when there is greater than sign or a colon. 我编写了此程序,该程序仅应在大于符号或冒号的情况下分解字符串。 When I enter for example "cars:ford> chevy" , the output gives me the space between the > and "chevy" and then the word "chevy. How do I prevent it from giving me that white space? All I want is the word , here is my code. 例如,当我输入“ cars:ford> chevy”时,输出将给我>和“ chevy”之间的空格,然后是单词“ chevy。如何防止它给我提供空白空间?字,这是我的代码。

import java.util.Scanner;
import java.util.StringTokenizer;

public class wp{
    public static void main(String[]args){

        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter words");

        String ingredients = keyboard.nextLine();

        StringTokenizer str = new StringTokenizer(ingredients,">:");

        while(str.hasMoreTokens()){
            System.out.println(str.nextToken());
        }

    }
}

As the space is part of the input, it is valid that the tokenizer returns it (think of situations where you want to react to the space). 由于空格是输入的一部分,因此令牌生成器返回它是有效的(考虑您要对空格作出反应的情况)。

So all you need to do is postprocess your split results eg: 因此,您要做的就是对拆分结果进行后处理,例如:

public class Main {

    public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter words");

        String ingredients = keyboard.nextLine();

        StringTokenizer str = new StringTokenizer(ingredients, ">:");

        while (str.hasMoreTokens()) {
            String nextToken = str.nextToken();
            String trimmed = nextToken.trim();
            System.out.println(trimmed);
        }

    }
}

Answer to trim is ok also, but on line 修剪的答案也可以,但是在线

StringTokenizer str = new StringTokenizer(ingredients, ">:");

you specified delimiters as characters '>' and ':' , you can simply add space there too. 您将分隔符指定为字符'>'':' ,也可以在其中简单地添加空格。 It depends what your requirements are. 这取决于您的要求。 If you want for string "cars:ford> chevy 123" to have 4 tokens, this is what you have to do... 如果要让字符串"cars:ford> chevy 123"具有4个令牌,这就是您要做的...

So change it to 因此将其更改为

StringTokenizer str = new StringTokenizer(ingredients, ">: ");

您可以使用String类的trim()方法删除所有之前和之后的空格: str.nextToken().trim()

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

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