Capitalize first character of all words

Input

 can you caplitalize?


Output

 Can You Caplitalize?


Code examples


JavaScript

class CapitalizeOnlyHeads {
	constructor(opt) {
	}
	convert(str = "") {
		return str.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
  }
};
module.exports = CapitalizeOnlyHeads;

if(!module.parent) {
  let capitalizer = new CapitalizeOnlyHeads();
  const str = " can you caplitalize?";
	console.log(capitalizer.convert(str));
}

PHP

<?php
class CapitalizeOnlyHeads {
  public function __construct($opt = []){
  }
  public function convert($str="") {
    return ucwords($str);
  }
}

if ( !isset(debug_backtrace()[0]) ) {
  $capitalizer = new CapitalizeOnlyHeads;
  $str = " can you caplitalize?";
  print($capitalizer->convert($str)."\n");
}

Perl

package CapitalizeOnlyHeads;
use strict;
use warnings;

sub new(){
  my $class = shift;
  my $self = {};
  return bless($self);
}

sub convert(){
  my $self = shift;
  my $str = shift;
  $str=~ s{^(\s*)([a-z])|(\s)([a-z])}{
    my $space = $1;
    my $space2 = $3;
    my $char = $2;
    my $char2 = $4;
    if($char) {
      $space.uc($char);
    }
    else{
      $space2.uc($char2);
    }
  }gesx;
  return $str;
}

if ($0 eq __FILE__) {
  my $capitalizer = new CapitalizeOnlyHeads();
  my $str = " can you caplitalize?";
  print($capitalizer->convert($str)."\n");
}
else{
  1;
}

Python

class CapitalizeOnlyHeads:
    def __init__(self, opt = {}):
        pass

    def convert(self, str):
        return str.title()

if __name__ == "__main__":
    capitalizer = CapitalizeOnlyHeads()
    str = " can you caplitalize?"
    print(capitalizer.convert(str))


Ruby

class CapitalizeOnlyHeads
  def initialize(opt = {} )
  end

  def convert(str)
    last_str = ""
    str.scan(/(\s*)([^\s]*)/) {|s| last_str += s[0]+s[1].capitalize }
    print(last_str)
  end
end

if $0 == __FILE__
  capitalizer = CapitalizeOnlyHeads.new()
  str = " can you caplitalize?";
  puts(capitalizer.convert(str))
end

Rust

Cargo.toml

[package]
name = "caplitalize_only_heads"
version = "0.0.1"

[dependencies]
inflections = "*"

[[bin]]
name = "caplitalize_only_heads"
path = "CaplitalizeOnlyHeads.rs"

CapitalizeOnlyHeads.rs

extern crate inflections;
use inflections::Inflect;
fn main() {
  let str = " can you caplitalize?";
  println!("{}", str.to_title_case());
}