2013-06-18 25 views
3

我需要从一个java字符串标记器中获取一个子字符串。我需要从一个Java字符串中得到一个子串字符串Tokenizer

我inpunt串是=披萨-1 *花生酱-20 *鸡-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 

我所需要的产品的价值,并在计数值单独的变量将这些值插入到数据库中。

我希望你能帮助我。

+0

你为什么不干脆更换'*'和'-'与空间? – Maroun

+0

你真的不应该使用'StringTokenizer',因为它的Javdocs状态。 –

+0

@MarounMaroun否,因为我需要将产品和计数放在单独的变量中,之后我必须将该值插入数据库。 – darthlitox

回答

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 
+0

非常感谢@RaviThapliyal。它的作品=) – darthlitox

+0

@darthlitox不要忘记标记答案是正确的:) –

+0

@darthlitox不客气。请接受答案,如果这可以解决您的问题。谢谢。 –

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(...); 

我会让你找出正确的索引子串()方法。

此外,而不是使用do/while循环结构最好是只使用一个while循环:

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

也就是说不要以为有一个令牌。

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); 
} 
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 
相关问题