2009-04-10 96 views

回答

41

使用substr與長度爲1,如:

$nth = substr($string, n-1, 1); 

另外查找perlmonks其他的解決方案。

21
$char = substr($mainstring, $i , 1); 

是一種做法,可能是最清晰的。

如果是你所想是數字價值,你打算做很多:

unpack("W*","hello") 

返回字符值的數組:

print join ",", unpack("W*","hello") ; 
# 104,101,108,108,111 

對於適當的Unicode/UTF8您可能想要使用的東西

use utf8; 
unpack("U*","hello\0ƀ\n") 
# 104,101,108,108,111,0,384,10 
+0

或者只是'ORD(SUBSTR($ mainstring,$ I,1))` – 2012-10-19 00:13:39

+0

事情是,通常當你想要一個字符的值,你希望所有的人的價值,並通過循環ord(substr())與解壓縮變體相比效率更低,難以閱讀,更難調試。 – 2012-11-18 08:33:37

2

Corol lary到其他substr()的答案是,你可以用它來設置值也在索引處。它支持這個左值或額外的參數。它也與拼接非常相似,這是相同的事情,但對於數組。

$string = "hello"; 
substr($string, 2, 2) = "this works?"; 
substr($string, 2, 2, "same thing basically"); 
@a = qw(s t r i n g s a n d t h i n g s); 
@cut_out = splice(@a, 2, 2); 
@cut_out = splice(@a, 2, 2, @replacement); 
相關問題