string 如何在 Perl 中的给定索引处获取字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/736616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get a character at a given index in Perl?
提问by Gdeglin
If I have a Perl string:
如果我有一个 Perl 字符串:
$str = "Hello";
how can I get a character at a given index similar to charAt(index)?
如何在类似于 charAt(index) 的给定索引处获取字符?
回答by dirkgently
回答by Kent Fredric
$char = substr( $mainstring, $i , 1 );
Is one way to do it, probably the clearest.
是一种方法,可能是最清楚的。
If what you were wanting was the numericvalue and you were intending to do this lots:
如果您想要的是数值并且您打算这样做:
unpack("W*","hello")
Returns an array of Char values:
返回一个 Char 值数组:
print join ",", unpack("W*","hello") ;
# 104,101,108,108,111
For proper Unicode/Utf8 stuff you might want to use
对于您可能想要使用的适当的 Unicode/Utf8 东西
use utf8;
unpack("U*","hello$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);
?\n")
# 104,101,108,108,111,0,384,10
回答by jettero
Corollary to the other substr() answers is that you can use it to setvalues at an index also. It supports this as lvalue or with extra arguments. It's also very similar to splice, which is the same thing, but for arrays.
其他 substr() 答案的推论是,您也可以使用它在索引处设置值。它支持将其作为左值或带有额外参数。它也与 splice 非常相似,是同一个东西,但用于数组。
##代码##回答by Siddharth Kumar Shukla
To get a character at the ith index, use substr. Eg: $str="Perl"; To fetch the 2nd index character, print substr($str,2,2). This will give the output r.
要获取第 i 个索引处的字符,请使用substr。例如: $str="Perl"; 要获取第二个索引字符,请打印 substr($str,2,2)。这将给出输出 r。