簡體   English   中英

如何使用Java從字符串中選取單個字符?

[英]How to pick up a single character from a string using Java?

例如, "this is yahoo answers" ,從這里開始,我要拾取每個字符並將其轉換為ASCII值。 我該怎么做?

您的問題有點含糊,但可能您想要這個嗎?

for (char c : "this is yahoo answers".toCharArray()) {
    System.out.println((int) c);
}

這將產生以下結果:

116
104
105
115
32
105
115
32
121
97
104
111
111
32
97
110
115
119
101
114
115

char轉換為int將顯示其代碼點

   String s = "stackoverflow.com"; 

    for(int i=0; i<s.length(); i++) {
     int ascii = (int) s.charAt(i) ;
     // .....
    }
for(int i = 0; i< theString.length; i++)
  theString.charAt(i);

如果要支持整個unicode范圍,包括6.0中的新表情符號( http://unicode.org/Public/6.0.0/charts/versioned/U1F600.pdf ),則可以嘗試以下操作:

for (int i=0, len=string.length(); i<len; ++i) {
    int codepoint = Character.codePointAt(string, i);
    if (codepoint > Character.MAX_VALUE) {
        ++i;
    }
    System.out.println(codepoint);
}

否則,如果您確定輸入僅是ascii,為什么不在這樣的代碼中聲明此假設:

byte[] ascii = string.getBytes("US-ASCII");
for (int i=0, len=ascii.length; i<len; ++i) {
    int ch = ascii[i];
    System.out.println(ch);
}

如果代碼恰好包含非ASCII字符,則應該拋出一個很好的異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM