2016-08-18 80 views
0

我想格式化特定的字符串。前幾天我遇到了筆記本電腦不幸的事件,並拿走了很多有價值的代碼。我確實保存了大部分文件,但少數未保存的文件對我的android應用程序至關重要。那麼這是我試圖格式化字符串的代碼。我需要每行開頭的所有數字消失。其中大約有3600個。使用Android Studio在JAVA中格式化字符串

//inside onCreate method 
String string = "3 import android.animation.Animator; \n" + 
"4 import android.animation.AnimatorListenerAdapter; \n" + 
"5 import android.animation.ValueAnimator; \n" + 
"6 import android.app.Activity; \n" + 
"7 import android.content.Context; \n" + 
"8 import android.content.DialogInterface; \n"; 

char[] ch = string.toCharArray(); 
    char c ='M'; 


    for(int i=4;i<ch.length;i++){ 
     boolean b1 = false; 
     boolean b2 = false; 
     boolean b3 = false; 
     boolean b4 = false; 
     c = ch[i]; 
     if((c >= '0' && c <= '9') && (ch[i-1]=='\n')){ 
      b1 = true; 

      if((ch[i+1] >= '0' && ch[i+1] <= '9'))b2=true; 

      if((ch[i+2] >= '0' && ch[i+2] <= '9'))b3=true;} 

     if(b1)ch[i]='Q'; 
     if(b2)ch[i+1]='Q'; 
     if(b3)ch[i+2]='Q'; 

     b1 = false; 
     b2 = false; 
     b3 = false; 
    } 

    String strings = ch.toString(); 
    strings.replace("Q",""); 

    Log.d("meoww","juy "+strings); 

正如你所看到的,for循環試圖爲我擺脫這些數字。日誌 顯示以下的輸出:

juy [[email protected] 

我知道它可能是一個小錯誤,但我該如何糾正這一問題。就像我說的,我將不得不在3600這個循環內做這個。

感謝您的任何建議,

繼續編碼

+0

使用'將String.valueOf替換這個()'而不是toString() – Jens

+0

如果它顯示類似'[C @ 3d03b1f5'這意味着它顯示對象的地址,而不是內部的內容...只是說 – bholagabbar

+0

嘗試'字符串字符串=新字符串(CH);'而不是'String strings = ch.toString();' –

回答

0

試試這個: String str = string.replaceAll("[0-9]","");

這將刪除所有數字。

+0

它將刪除字符串中的所有數字,所以它可以刪除任何數字目前的代碼也??? –

+0

它將用空值替換String中的所有數字。所以是的。 –

+0

我不能擁有新數組中使用的數字,因爲循環和字母數字變量名稱被刪除。 @Vygintas B –

0

嘗試使用此:

public static void main(String[] args) 
     {// inside onCreate method 
     String string = "3 import android.animation.Animator; \n" 
      + "4 import android.animation.AnimatorListenerAdapter; \n" 
      + "5 import android.animation.ValueAnimator; \n" + "6 import android.app.Activity; \n" 
      + "7 import android.content.Context; \n" + "8 import android.content.DialogInterface; \n" 
      + "17 import android.content.Context; \n" + "558 import android.content.DialogInterface; \n"; 

     char[] ch = string.toCharArray(); 
     if(ch[0] > '0' && ch[0] < '9'){ 
      ch[0] = ' '; 
     } 
     for (int i = 0; i < ch.length; i++) 
     { 
      if (ch[i] == '\n') 
      { 
      int count = i + 1; 
      if (count < ch.length) 
      { 
       while (count < ch.length && ch[count] >= '0' && ch[count] <= '9') 
       { 
       ch[count] = ' '; 
       count++; 
       } 
      } 
      } 
     } 

     String strings = new String(ch); 

     System.out.println(strings); 
     } 

該代碼將在與空間的每一行的第一位置更換次數。在此之後,您可以應用eclipse格式化程序刪除不必要的空間。

1

此代碼

String.replaceAll ("^\d*\s", " ")這將花費數在由多個數字\d*之一以下行^的開頭,後跟一個空格,並用空格

+0

這應該是接受答案+1 –

+0

這可能會做的伎倆。只要我測試一下,我會立即投入。希望它不會刪除用於數組或循環構造的關鍵數字。 @Scary袋熊 –