【问题标题】:A Perl Program Which divides a String by spaces between them?一个 Perl 程序,它用它们之间的空格来分割一个字符串?
【发布时间】:2013-06-25 10:55:25
【问题描述】:

我希望我的程序将字符串除以它们之间的空格

$string = "hello how are you";  

输出应该是这样的:

hello  
how  
are  
you

【问题讨论】:

  • 如果不是全部粗体大写,我们可能会更好地阅读。
  • 你做了什么研究?这是一个非常基本的要求。

标签: perl split


【解决方案1】:

您可以通过几种不同的方式做到这一点。

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) = ...

【讨论】:

  • 我不明白为什么有人会对此投反对票。这是一流的答案,大多数时候来自 TLP。
  • @NikhilJain 谢谢。是的,别担心,随机 DV 会发生。
【解决方案2】:

我觉得很简单....

$string = "hello how are you";  
print $_, "\n" for split ' ', $string;

【讨论】:

    【解决方案3】:

    @Array = split(" ",$string); 然后@Array 包含答案

    【讨论】:

      【解决方案4】:

      您需要一个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 循环更具可读性。
      • @TLP:感谢您的解释。我采用了 OP 给出的相同示例,这就是我使用单个空格的原因。
      • 我之前没有注意到,但似乎这个问题的 3/4 答案被否决了(包括我的答案)。所以也许它只是一个连续的downvoter,没什么好担心的。
      【解决方案5】:

      如果有多余的空格,用正则表达式分割:

      my $string = "hello how are you";
      my @words = split /\s+/, $string; ## account for extra spaces if any
      print join "\n", @words
      

      【讨论】:

        猜你喜欢
        • 2011-03-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多