2014-03-30 81 views
-1

我有一段文字,我需要逐字阅读,直到';'分隔符... 我在许多地方搜索过,也阅读过一些章节,但找不到任何方法使用...请帮助!如何从字符串中读取并拆分某些单词?

要读取的字符串,即32;土豆;蔬菜; 21.30; 12.20; 15 21 32 45;

+1

[将Java字符串拆分为两个字符串使用分隔符](http://stackoverflow.com/questions/7787385/split-java-string-into-two-string-using-delimiter) – McDowell

+0

http:// docs.oracle.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String) – Srinath

+0

有一个确切的重复你在这里问 - > http:// stackoverflow /我的问题/ 3481828 /如何拆分字符串在java中 –

回答

0

试试这个:

for (String s : myOwnString.split(";")){ 
    System.out.println(s); 
} 
0

Java支持这个很清楚,与String.split()方法。您可以阅读文档here

String[] tokens = input.split(";"); 

// tokens contains each value. 
+0

thnx :)我也试过这 – s33h

0

可以使用的Stringsplit方法。

String string = "32; Potatoe; Vegetables; 21.30; 12.20; 15 21 32 45"; 
String[] split = string.split(";"); 

for(String s: split) 
{ 
    System.out.println(s); 
} 

这将打印:

32 
Potatoe 
Vegetables 
21.30 
12.20 
15 21 32 45 
+0

thnx我做到了这一点,但我不能解析为int例如:id = Integer.parseInt(s );我得到一个错误 – s33h

0
String text = "32; Potatoe; Vegetables; 21.30; 12.20; 15 21 32 45"; 
String[] words = new String[text.length()]; 
int initialIndex = 0,i=0; 

while (initialIndex<text.length()) { 
    words[i] = text.substring(initialIndex, text.indexOf(";")); 
    i++; 
    initialIndex = text.indexOf(";")+1; 
    } 

现在的话字符串包含文本中所有单词。 您可以通过 访问word.get(index);

1
String s = "32; Potatoe; Vegetables; 21.30; 12.20; 15 21 32 45;"; 
String[] splittedWords; 

splittedWords = s.split(";"); 

您可以使用split方法沿分隔符分隔单词。它会返回一个字符串列表。 如果你想在字符串中的值解析为一个整数,你可以这样做:

for (String string : splittedWords) 
    { 
     if(string.matches("[^a-z \\.]+")==true) 
     { 
      int value = Integer.parseInt(string); 

      System.out.println(value); 
     } 
    } 

在samplestring唯一的整数为32,虽然。这就是为什么这个代码只会输出“32”。

+0

我做到了,但我无法解析从字符串到INT,我试图转换与增强的for循环 – s33h

+1

thnx再次回答时出现错误..我尝试了几件事情包括你做了什么,但没有产生所需的输出。对于解释:32是产品编号,而其他是名称,类别,价格和数量。我想添加数量,但是我不能...... thnx再次:) – s33h

+0

没有问题......当然也可以解析其他值,但这需要更复杂一点的算法。 – Iconstrife

相关问题