java中String中數字提取到數組中


實現效果:從String中將連續數字提取到泛型數組(考慮了負數、浮點數、連續數字首位可能爲0 等特殊情況)

運行效果圖:





函數代碼:


public ArrayList<Double>  NumberString(String str)
{
     str=str.trim();//去除字符串首尾空格
//保存分割後的數字
ArrayList<Double>  array;
        array = new ArrayList<>();
boolean start;//連續數字字符開始的標誌
        start = false;
boolean point=false;//浮點數標識
boolean negative=false;//負數標識
double Num;
//去除String中的其他字符,保留數字
if(str!=null&&!"".equals(str))//str不爲空,且不爲空串(空格算字符)
{
    StringBuilder  number = new StringBuilder();//暫時保存數字
//遍歷每個字符
for(int i=0;i<str.length();i++)
 {
           
//字符爲數字
if(str.charAt(i)>=48&&str.charAt(i)<=57)
  {
start=true;
//number+=str.charAt(i);
//"-","."字符特殊處理
  if(negative==true)
{   
number=number.append('-');
negative=false;
}
if(point==true)

number.append('.');
point=false;
}

number=number.append(str.charAt(i));

  }
//"-"字符
else if (str.charAt(i)=='-')
{
negative=true;
}
//"."字符
else if(str.charAt(i)=='.')
{
point=true;
}
//字符不爲數字,"-","."
else
  {

//"-""."的特殊處理
if(negative==true)
{
negative=false;
}
if(point==true)
{
point=false;
}
start=false;
if(number.length()!=0)
      {
String temp=number.toString();//轉換爲String
temp=ToNumber(temp);//去除首位可能的0
Num=Double.parseDouble(temp);//轉換爲數字
//number=number.delete(0, number.length()-1);//重新置null
number=new StringBuilder();
array.add(Num);
       }
   }

//最後一位字符爲數字時,需要特殊處理
if(i==str.length()-1)
     {
     if(number.length()!=0)
      {

String temp=number.toString();//轉換爲String
temp=ToNumber(temp);//去除首位可能的0
Num=Double.parseDouble(temp);//轉換爲數字
//number=number.delete(0, number.length()-1);//重新置null
number=new StringBuilder();
array.add(Num);
       }    
    }

 }

return array;
}

else
{
return null;
}  

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章