How can I capitalize the first letter of each word?

前端 未结 20 2335
暖寄归人
暖寄归人 2021-01-14 12:31

I need a script in any language to capitalize the first letter of every word in a file.

Thanks for all the answers.

Stackoverflow rocks!

相关标签:
20条回答
  • 2021-01-14 12:35

    Scala:

    scala> "hello world" split(" ") map(_.capitalize) mkString(" ")
    res0: String = Hello World
    

    or well, given that the input should be a file:

    import scala.io.Source
    Source.fromFile("filename").getLines.map(_ split(" ") map(_.capitalize) mkString(" "))
    
    0 讨论(0)
  • 2021-01-14 12:37

    Using the non-standard (Gnu extension) sed utility from the command line:

    sed -i '' -r 's/\b(.)/\U\1/g' file.txt
    

    Get rid of the "-i" if you don't want it to modify the file in-place.

    note that you should not use this in portable scripts

    0 讨论(0)
  • 2021-01-14 12:38

    A simple perl script that does this: (via http://www.go4expert.com/forums/showthread.php?t=2138)

    sub ucwords {
      $str = shift;
      $str = lc($str);
      $str =~ s/\b(\w)/\u$1/g;
      return $str;
    }
    
    while (<STDIN>) {
        print ucwords $_;
    }
    

    Then you call it with

    perl ucfile.pl < srcfile.txt > outfile.txt
    
    0 讨论(0)
  • 2021-01-14 12:40

    C#:

    string foo = "bar baz";
    foo = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(foo);
    //foo = Bar Baz
    
    0 讨论(0)
  • 2021-01-14 12:40

    zsh solution

    #!/bin/zsh
    mystring="vb.net lOOKS very unsexy"
    echo "${(C)mystring}"
    Vb.Net Looks Very Unsexy
    

    Note it does CAP after every non alpha character, see VB.Net .

    0 讨论(0)
  • 2021-01-14 12:43

    In ruby:

    str.gsub(/^[a-z]|\s+[a-z]/) { |a| a.upcase }
    

    hrm, actually this is nicer:

    str.each(' ') {|word| puts word.capitalize}
    
    0 讨论(0)
提交回复
热议问题