我需要从Java字符串Tokenizer获取子字符串
作者:互联网
我需要从Java字符串令牌生成器获取子字符串.
我的插入字符串是= 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
我需要将产品值和计数值放在单独的变量中,以便将该值插入数据库中.
我希望你能帮助我.
解决方法:
您可以使用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
标签:tokenize,substring,netbeans,string,java 来源: https://codeday.me/bug/20191123/2065369.html