loading...

Daily Challenge #188 - Break camelCase

thepracticaldev profile image dev.to staff ・1 min read

Write a function that will turn a camelCase word into a regular one by adding spaces and lower-casing the words.

Examples

ccbreaker("camelCasing") == "camel casing"
ccbreaker("garbageTruck") == "garbage truck"

Tests

ccbreaker("policeSiren") == "police siren"
ccbreaker("camelCasingTest") =="camel casing test"`

Good luck!


This challenge comes from hakt on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

Posted on by:

thepracticaldev profile

dev.to staff

@thepracticaldev

The hardworking team behind dev.to ❤️

Discussion

markdown guide
 

Java Streams

public String ccbreaker(String input) {
    return Arrays.stream(input.split(""))
            .map(s -> s.matches("[A-Z]") ? " " + s.toLowerCase() : s)
            .collect(Collectors.joining());
}
 

JavaScript using regex

function ccbreaker(str) {
  const regex = /([a-z])([A-Z])/g;
  const spaces = str.replace(regex, '$1 $2');
  const lowercase = spaces.toLowerCase();
  return lowercase;
}
 

dart

String ccbreaker(String value) {
  var words = List<String>();
  var word = "";
  for(var idx = 0; idx < value.length; idx++) {
    if(value[idx] == value[idx].toUpperCase()) {
      words.add(word);
      word = value[idx].toLowerCase();
    } else {
      word += value[idx];
    }
  }
  if(!word.isEmpty) words.add(word);
  return words.join(" ");
}
 

C++ solution

string ccbreaker(string camelCased){
    string nonCamelCased = ""; // string that is ragular one
    for(char c : camelCased){
        // whenever a upper case letter is encountered first add a space
        // and then add its lower case version
        if(c <= 90 && c >= 65){
            nonCamelCased += " ";
            nonCamelCased += char(c+32);
        }
        // if not uppercase then simply add it
        else{
            nonCamelCased += c;
        }
    }
    return nonCamelCased;
}
 

Python

def ccbreaker(a):
        if a.isupper() == True:
                print(' '+a.lower(), end= '')
        else:
                print(a, end='')

var = input("Enter the camelCase: ")
var = list(var)
for i in var:
        ccbreaker(i)
 

Java

class Main {
  public static void main(String[] args) {
    System.out.println("Hello world!");
    String cad = "camelCaseTesting";
    String unCammel = "";
    for(int i = 0; i < cad.length(); i++){
      int actual = cad.charAt(i);
      if(actual > 64 && actual < 91){
        unCammel+=" "+(char)actual;
      }else{
        unCammel += (char)actual;
      }
    }
    unCammel = unCammel.toLowerCase();
    System.out.println(unCammel);
  }
}
 
function ccbreaker(string $input): string {
    return preg_replace_callback(
        '/[A-Z]/',
        fn (array $match): string => ' '. chr(ord($match[0]) + 32),
        $input
    );
}

Rare case where PHP is concise.

3v4l.org/1vCqj

 

python

import re


def ccbreaker(in_str):
    return re.sub('([a-z])([A-Z])', r'\1 \2', in_str).lower()


# ---------------
print ccbreaker('camelCasing')
print ccbreaker('garbageTruck')
print ccbreaker('camelCasingTest')

 

In rust!

pub fn ccbreaker (value: &str) -> String {
    value.chars()
        .into_iter()
        .map(|c| 
            if c.is_uppercase() {
                format!(" {}", c.to_lowercase())
            } else { 
                c.to_string()
            })
        .collect::<String>()
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn example_1() {
        assert_eq!(ccbreaker("camelCasing"), "camel casing".to_string());
    }
    #[test]
    fn example_2() {
        assert_eq!(ccbreaker("garbageTruck"), "garbage truck".to_string());
    }
    #[test]
    fn test_1() {
        assert_eq!(ccbreaker("policeSiren"), "police siren".to_string());
    }
    #[test]
    fn test_2() {
        assert_eq!(ccbreaker("camelCasingTest"), "camel casing test".to_string());
    }
}

Rust Playground
GitHub Gist

 

The link seems to be after a completely different test

function ccbreaker(str){
  return str.split(/(?=(?:[A-Z]))/g)
 .map(word=>word.toLowerCase())
 .join(' ')
}
 

Ruby:

def ccbreaker(s)
  s.gsub(/([A-Z])/) { |l| " #{$1}".downcase }
end