【发布时间】:2013-06-25 10:55:25
【问题描述】:
我希望我的程序将字符串除以它们之间的空格
$string = "hello how are you";
输出应该是这样的:
hello
how
are
you
【问题讨论】:
-
如果不是全部粗体大写,我们可能会更好地阅读。
-
你做了什么研究?这是一个非常基本的要求。
我希望我的程序将字符串除以它们之间的空格
$string = "hello how are you";
输出应该是这样的:
hello
how
are
you
【问题讨论】:
您可以通过几种不同的方式做到这一点。
use strict;
use warnings;
my $string = "hello how are you";
my @first = $string =~ /\S+/g; # regex capture non-whitespace
my @second = split ' ', $string; # split on whitespace
my $third = $string;
$third =~ tr/ /\n/; # copy string, substitute space for newline
# $third =~ s/ /\n/g; # same thing, but with s///
前两个使用单个单词创建数组,最后一个创建不同的单个字符串。如果您只想打印一些东西,那么最后一个就足够了。要打印数组,请执行以下操作:
print "$_\n" for @first;
注意事项:
/(\S+)/,但当使用 /g 修饰符并省略括号时,将返回整个匹配项。my ($var) = ...
【讨论】:
我觉得很简单....
$string = "hello how are you";
print $_, "\n" for split ' ', $string;
【讨论】:
@Array = split(" ",$string); 然后@Array 包含答案
【讨论】:
您需要一个split 来将字符串除以空格,例如
use strict;
my $string = "hello how are you";
my @substr = split(' ', $string); # split the string by space
{
local $, = "\n"; # setting the output field operator for printing the values in each line
print @substr;
}
Output:
hello
how
are
you
【讨论】:
use warnings,你不应该在一个空格上分割,除非你在设计上想要多个连续空格的空字段,使用用于打印的块是有效代码,但看起来很奇怪,$, 对某些人来说可能是模糊的,而 for 循环更具可读性。
如果有多余的空格,用正则表达式分割:
my $string = "hello how are you";
my @words = split /\s+/, $string; ## account for extra spaces if any
print join "\n", @words
【讨论】: