DEV Community

dev.to staff
dev.to staff

Posted on

Daily Challenge #188 - Break camelCase

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!

Top comments (10)

Collapse
 
joemaffei profile image
Joe Maffei

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;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mategreen profile image
matej

Java Streams

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

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(" ");
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
vidit1999 profile image
Vidit Sarkar

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;
}
Collapse
 
maskedman99 profile image
Rohit Prasad

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)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
josuerodriguez98 profile image
Josué Rodríguez (He/Him)

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);
  }
}
Collapse
 
pmkroeker profile image
Peter • Edited

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

Collapse
 
fjones profile image
FJones • Edited
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

Collapse
 
amcmillan01 profile image
Andrei McMillan

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')

Collapse
 
georgewl profile image
George WL

The link seems to be after a completely different test

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