我讀取一個文本文件並將數據放入String
的ArrayList
。如何從字符串ArrayList中只拾取整數數據
的數據是一樣
China 12351235123 Korea 123532523 USA 12341235123
我只需要那些整數數據作爲一個整數找到整數的第一位。我知道如何找到第一個數字,但我不知道如何只能拾取整數數據。
我讀取一個文本文件並將數據放入String
的ArrayList
。如何從字符串ArrayList中只拾取整數數據
的數據是一樣
China 12351235123 Korea 123532523 USA 12341235123
我只需要那些整數數據作爲一個整數找到整數的第一位。我知道如何找到第一個數字,但我不知道如何只能拾取整數數據。
我假設你的ArrayList
是String
類型。 replaceAll()
會拿出什麼,是不是數字(0-9)
ArrayList<String> countrys = new ArrayList<String>();
countrys.add("China 12351235123");
countrys.add("Korea 123532523");
countrys.add("USA 12341235123");
for(String c:countrys){
String number = c.replaceAll("[^0-9]", "");
System.out.println(number);
}
您可以使用正則表達式作爲SLY建議,或者你可以去超過你的清單,拆分對象分爲兩個部分:「國家」和「編號」用:
for(String s : array){
String[] parts = s.split(" ");
long number = Long.parseLong(parts[1]);
System.out.println(number);
}
注:不變的是,每個元件包含兩個部分與所述分隔符「空白」,而第二部分是一個數字。
我不需要那些字符串數據,但我只需要整數數據來查找它們的第一個數字。 – Nakseung
您可以在代碼中使用正則表達式和將要小心,不是所有的數字可以在整數的範圍......所以長材列表下面
public static void main(String[] args) {
List<Long> longList = new ArrayList<Long>();
Pattern pattern = Pattern.compile("\\w+([0-9]+)");// regex pattern
for (String string : listOfCountriesAndNumbers) {
Matcher matcher = pattern.matcher(string);
for (int i = 0; i < matcher.groupCount(); i++) {
matcher.find();
longList.add(Long.parseLong(matcher.group()));
}
}
System.out.println(longList);
}
試試這個:
// Creation of ArrayList of string
ArrayList<String> obj = new ArrayList<String>();
// arrayList of string
obj.add("China 12351235123");
obj.add("Korea 123532523");
obj.add("USA 12341235123");
Iterator<String> iterator = obj.iterator();
String str;
String[] split_str;
long value;
while (iterator.hasNext()) {
str = iterator.next().toString();
split_str = str.split(" ");
String split_2 = split_str[1];
value = Long.parseLong(split_2);
System.out.println(value);
}
請告訴我們你到目前爲止試過的東西。 – TDG
String的ArrayList將不接受整數。它可能是對象的ArrayList。是嗎 ?或者「中國12351235123」是單個字符串? –
也許[This](http://stackoverflow.com/questions/1903252/extract-integer-part-in-string)可以幫助 –