我正在將帳戶詳細信息(帳戶名稱和帳戶餘額)讀取到字符串數組中。典型值將如{"Cash on hand -4871266","SB Account 976369","Current Account 980980"}
。我想將字符串數組拆分爲兩個 - 第一個數組應包含帳戶名稱,第二個數組應包含帳戶餘額。由於帳戶名稱可能包含空格,因此無法根據空白拆分數組。我如何在Java中實現這一點將字符串拆分爲數字數據和其他數字數據
0
A
回答
1
您可以使用substring()
進行拆分,並使用lastIndexOf()
來獲取最後一個空格索引。
String x[] = {"Cash on hand -4871266","SB Account 976369","Current Account 980980"};
String arr1[] = new String[x.length], arr2[] = new String[x.length];
for(int i=0; i<x.length; i++)
{
arr1[i] = x[i].substring(0,x[i].lastIndexOf(" ")); //account name
arr2[i] = x[i].substring(x[i].lastIndexOf(" ")+1); //value
}
0
如果帳戶名犯規包括數字,那麼你可以用行話-?\\d+
剝離出量
Pattern p = Pattern.compile("-?\\d+");
String[] accounts = {"Cash on hand -4871266","SB Account 976369","Current Account 980980"};
for(String account : accounts){
Matcher m = p.matcher(account);
while (m.find()) {
System.out.println(m.group());
}
}
0
試試下面的辦法:
public class Main {
public static void main(String[] args) {
List<String> stringList = new ArrayList<>();
stringList.add("Cash on hand -4871266");
stringList.add("SB Account 976369");
stringList.add("Current Account 980980");
for (String str : stringList) {
// Extracts the left hand-side of your string
System.out.println(str.replaceAll("[\\s-+][0-9]+", ""));
// Extracts the right hand-side of your string
Pattern testPattern = Pattern.compile("[\\s-+][0-9]+");
Matcher matcher = testPattern.matcher(str);
matcher.find();
System.out.println(matcher.group().trim());
}
}
}
相關問題
- 1. 將字符串拆分爲字母數字和其他字符
- 2. 將r中的數據幀拆分爲字符和數字
- 3. Autohotkey:將連接字符串拆分爲字符串和數字
- 4. C#拆分字符串 - 將字符串拆分爲數組
- 5. 從字符數據中拆分數字
- 6. 如何將字符串拆分爲字母字符串和數字字符串?
- 7. C++如何將字符串拆分爲字符串和整數?
- 8. 將字符串拆分爲整數和字符串C++
- 9. 將字符串拆分爲字母和數字
- 10. Django從數據庫拆分字符串
- 11. 從字符串拆分數據到列
- 12. 拆分字符串插入數據庫
- 13. ColdFusion |拆分數據庫字符串
- 14. 將字符串拆分爲數組C
- 15. 將字符串拆分爲數組Shellllscript
- 16. Android將字符串拆分爲數組
- 17. 將字符串拆分爲雙數組
- 18. 將字符串拆分爲數組C++
- 19. 將字符串拆分爲數組
- 20. Bash:將字符串拆分爲數組
- 21. Elisp拆分字符串函數來拆分字符串。字符
- 22. 將字符串拆分爲字符和整數C++
- 23. Java:將字符串方程拆分爲數字和運算符
- 24. 將數字字符串拆分爲數組
- 25. PHP preg_split:將字符串拆分爲其他字符串
- 26. 如何將字符串分數和數字轉換爲數字?
- 27. Swift 3:按字符串將字符串拆分爲數組
- 28. 如何將字符串拆分爲字符串數組?
- 29. 將字符串拆分爲字符串數組
- 30. 將字符串拆分爲字符串數組
分裂接受正則表達式,所以你可以拆分在最後一個空白處 – SomeJavaGuy
看看正則表達式(java.util.regex.Pattern)。然後你可以像「字符組」分割空白「數字」 –
尋找最右邊的空間:) https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#lastIndexOf( INT) – Koshinae