我需要从java字符串Tokenizer获取子字符串

时间:2013-06-18 21:06:41

标签: java string netbeans substring tokenize

我需要从java字符串标记器中获取子字符串。

我的inpunt字符串是= Pizza-1 * Nutella-20 * Chicken-65 *

        StringTokenizer productsTokenizer = new StringTokenizer("Pizza-1*Nutella-20*Chicken-65*", "*");
        do
        {
            try
            {
                int pos = productsTokenizer .nextToken().indexOf("-");
                String product = productsTokenizer .nextToken().substring(0, pos+1);
                String count= productsTokenizer .nextToken().substring(pos, pos+1);
                System.out.println(product + "   " + count);
            }
            catch(Exception e)
            {

            }
        }
        while(productsTokenizer .hasMoreTokens());

我的输出必须是:

Pizza  1
Nutella  20
Chicken  65

我需要在单独的变量中使用产品值和计数值来将这些值插入数据库中。

我希望你能帮助我。

4 个答案:

答案 0 :(得分:3)

您可以使用String.split()作为

String[] products = "Pizza-1*Nutella-20*Chicken-65*".split("\\*");

for (String product : products) {
    String[] prodNameCount = product.split("\\-");
    System.out.println(prodNameCount[0] + " " + prodNameCount[1]);
}

输出

Pizza  1
Nutella  20
Chicken  65

答案 1 :(得分:0)

您调用nextToken()方法3次。这将为您提供3种不同的令牌

int pos = productsTokenizer .nextToken().indexOf("-");
String product = productsTokenizer .nextToken().substring(0, pos+1);
String count= productsTokenizer .nextToken().substring(pos, pos+1);

相反,你应该做类似的事情:

String token = productsTokenizer .nextToken();
int pos = token.indexOf("-");
String product = token.substring(...);
String count= token.substring(...);

我会让你弄清楚substring()方法的正确索引。

另外,不使用do / while结构,最好只使用while循环:

while(productsTokenizer .hasMoreTokens())
{
    // add your code here
}   

这不要假设有一个令牌。

答案 2 :(得分:0)

如果您的输入增长,您可能想要使用的替代答案:

// find all strings that match START or '*' followed by the name (matched),
// a hyphen and then a positive number (not starting with 0)
Pattern p = Pattern.compile("(?:^|[*])(\\w+)-([1-9]\\d*)");
Matcher finder = p.matcher(products);
while (finder.find()) {
    // possibly check if the new match directly follows the previous one
    String product = finder.group(1);
    int count = Integer.valueOf(finder.group(2));
    System.out.printf("Product: %s , count %d%n", product, count);
}

答案 3 :(得分:0)

有些人不喜欢正则表达式,但这对他们来说是一个很好的应用。您需要使用"(\\w+)-(\\d{1,})\\*"作为模式。这是一个玩具示例:

    String template = "Pizza-1*Nutella-20*Chicken-65*";
    String pattern = "(\\w+)-(\\d+)\\*";

    Pattern p = Pattern.compile(pattern);
    Matcher m = p.matcher(template);

    while(m.find())
    {
        System.out.println(m.group(1) + " " + m.group(2)); 
    }

为了解释这一点,"(\\w+)-(\\d+)\\*"会查找(\\w+)[A-Za-z0-9_]中的至少1个字符,后跟-,数字为\\d+,其中+表示长度至少为一个字符,后跟*,必须对其进行转义。括号捕捉到它们内部的内容。此正则表达式中有两组捕获括号,因此我们通过group(1)group(2)引用它们,如while循环中所示,它打印出来:

Pizza 1
Nutella 20
Chicken 65