2014-11-04 75 views
0

如何將字符串轉換爲字符數組但只有一種扭曲:只應將大寫字母放入字符數組中。從字符串中選擇大寫字母並將它們轉換爲字符數組

例如

  • 輸入字符串"abCcAB123"
  • 輸出字符數組{C,A,B}
+0

你可以張貼一些代碼,你試過嗎? – Ajit 2014-11-04 08:48:53

+5

先刪除小寫字母(例如使用正則表達式),然後使用toCharArray()。 – sp00m 2014-11-04 08:51:02

+2

投票結束,因爲OPs缺乏努力。 – 2014-11-04 08:52:09

回答

1

,你可以這樣做:

public static void main(String[] args) { 
     String s="ab [email protected]#$&*()//CcAB897987"; 
     List upperChar=new ArrayList(); 
     String a = s.replaceAll("[^A-Z\\-]", ""); // remove all character other Uppercase character 
     char []ch=a.toCharArray();    // this contains all uppercase character 
     for (int i = 0; i < ch.length; i++) { 
       upperChar.add(ch[i]);    // make a list of uppercase char. 
     } 

      System.out.println(upperChar); 

} 

輸出:

[C, A, B] 
+0

我試過你的代碼,但它只是刪除小寫,但其他的關鍵字像數字仍然存在 – priyank 2014-11-04 10:29:09

+0

然後把'[a-z0-9]'而不是'[az]' – Rustam 2014-11-04 10:32:12

+0

[ a-z0-9]會從字符串中刪除小寫字母和數字,但像「!@#」這樣的特殊字符仍然存在於數組中,因此請您提供代碼以刪除所有特殊字符 – priyank 2014-11-05 18:28:54

1

Rmove所有非大寫字母,然後轉換成字符數組。

String str = "abCcAB"; 
String a = str.replaceAll("[^A-Z]", ""); 
System.out.println(a.toCharArray()); 
+0

我已經試過你的代碼,但它只是刪除小寫,但其他的關鍵字像數字仍然存在 – priyank 2014-11-04 10:28:38

+0

你試過了哪個字符串。我不明白爲什麼任何數字仍然存在。 – Steffen 2014-11-04 11:16:15

+0

我試過字符串「abCcAB123」 – priyank 2014-11-05 18:26:16

0

psedocode:

queue output; //declaration of the character array for output 
    while(input.length!=0){ //checking the length of the input array 
     firstcharacter=string.charAt(0); //getting the firstCharacter of the input string 
     if(character.IsUpperCase(firtcharacter)){ //checking if the firstCharacter is uppercase 
      output.enqueue(firtcharacter); //if the character is uppercase add to the array 
     } 
     input=input.substring(1,string.length); //remove the first character from the string 
    } 
//output should now contain all the uppercase characters. 

這背後是解決問題的邏輯。

0

試試這個:

public class CaptialChars { 
    public static void main(String[] args){ 
     String input="SaGaR"; 
     char[] output=input.replaceAll("[a-z]", "").toCharArray(); 
     for(char character:output){ 
      System.out.println(character); 
     } 

    } 
} 
相關問題