[英]Identify the Element in String array in java
我想識別String數組中字母和數字中的元素,還有其他方法嗎?
String a[]={"aaaa","111111","bbbbbb"};
for(int i=0;i<a.length;i++)
{
post your code for this FOR LOOP
}
他們說您有問題...所以您選擇正則表達式來解決它,現在您有兩個問題。 :-)
但是,如果速度不是什么大問題,則可以嘗試一下,前提是您具有良好的單元測試。 類似於以下內容:
public static void testRegularExpressionForElement() {
String[] a = new String[] {"test1", "13", "blah", "1234.44"};
Pattern pattern = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+");
for (String element : a) {
if (pattern.matcher(element).matches()) {
System.out.println(element + " is a number");
} else {
System.out.println(element + " is not a number");
}
}
}
上面的好處是,您可以調整表達式以完全匹配所需的內容。
另一種方法是使用Integer.parseInt()並捕獲異常,但這在將異常用於邏輯時這是不好的編程。
遍歷數組並編寫一個函數來檢查isNumeric是否。
for (a1 : a){
boolean isNumbr= isNumeric(a1);
}
...
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.