How can I capitalize the first letter of each word?

前端 未结 20 2322
暖寄归人
暖寄归人 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:32

    php uses ucwords($string) or ucwords('all of this will start with capitals') to do the trick. so you can just open up a file and get the data and then use this function:

    <?php 
    $file = "test.txt"; 
    $data = fopen($file, 'r');
    $allData = fread($data, filesize($file));
    fclose($fh);
    echo ucwords($allData);
    ?>
    

    Edit, my code got cut off. Sorry.

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

    perl:

    $ perl -e '$foo = "foo bar"; $foo =~ s/\b(\w)/uc($1)/ge; print $foo;'
    

    Foo Bar

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

    From the shell, using ruby, this works assuming your input file is called FILENAME, and it should preserve all existing file formatting - it doesn't collapse the spacing as some other solutions might:

    cat FILENAME | ruby -n -e 'puts $_.gsub(/^[a-z]|\s+[a-z]/) { |a| a.upcase }'
    
    0 讨论(0)
  • 2021-01-14 12:34

    This is done in PHP.

    $string = "I need a script in any language to capitalize the first letter of every word in a file."
    $cap = ucwords($string);
    
    0 讨论(0)
  • 2021-01-14 12:34

    Very basic version for AMOS Basic on the Amiga — only treats spaces as word separators though. I'm sure there is a better way using PEEK and POKE, but my memory is rather rusty with anything beyond 15 years.

    FILE$=Fsel$("*.txt")
    Open In 1,FILE$
    Input #1,STR$
    STR$=Lower$(STR$)
    L=Len($STR)
    LAST$=" "
    NEW$=""
    For I=0 to L-1
      CUR$=MID$(STR$,I,1)
      If LAST$=" "
        NEW$=NEW$+Upper$(CUR$)
      Else
        NEW$=NEW$+$CUR$
      Endif
      LAST$=$CUR$
    Next
    Close 1
    Print NEW$
    

    I miss good old AMOS, a great language to learn with... pretty ugly though, heh.

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

    In Python, open('file.txt').read().title() should suffice.

    0 讨论(0)
提交回复
热议问题