이 페이지는 코딩도장 데이터의 읽기 전용 정적 보관본입니다.

CamelCase를 Pothole_case 로 바꾸기!

파이썬과 같은 몇몇 프로그래밍 언어는 Pothole_case 를 더 선호하는 언어라고 합니다.

Example:

codingDojang --> coding_dojang

numGoat30 --> num_goat_3_0

위 보기와 같이 CameleCase를 Pothole_case 로 바꾸는 함수를 만들어요!

출처: UT past test

2015/06/21 11:53

Jethro

+1 문제가 살짝 애매모호합니다. 한 camelCase 스트링만 pothole_case 로 변경할 수 있는 함수만 만들면 되는 것인지? 아니면 camelCase 가 있는 text 를 읽어와 모든 camelCase 를 pothole_case 로 변경해서 저장하는 함수를 만들라는 것인지요?? 전 후자인 줄 알고 한참을 생각하고 있는데 풀이를 보니 전자들로 풀으셨더라구요. 어떤게 출제자의 의도일까요? - 예강효빠, 2017/04/13 11:42

210개의 풀이가 있습니다.

파이썬입니다.

import re

pc = lambda src: re.sub("([A-Z0-9])", lambda m:"_"+m.group().lower(), src)

print(pc("codingDojang"))  # coding_dojang
print(pc("numGoat30"))     # num_goat_3_0

첫번째 문자가 대문자인 경우는 생각하지 않고 대문자나 숫자인 경우 무조건 "_"+소문자로 변경하도록 했습니다.

2015/06/23 17:57

pahkey

안녕하세요~ 혹시 re.sub의 두번째 인수인 lambda m에서 m에 어떻게 값이 전달되는지 알 수 있을까요? 사용자는 src만 넘겨주는데, 파이썬의 어떤 문법적 근거로 저게 가능한지 궁금하네여 - 김 매미, 2015/11/02 16:29
+1 re.sub 을 위처럼 사용하면 함수를 인자로 전달받을 수 있습니다. 여기서 함수는 lambda를 이용한거구요, re.sub 에서 사용된 함수의 파라미터는 정규식에 매치되는 match object입니다. 결국 re.sub가 그 역할을 해준다고 봐야 할 것 같네요. - pahkey, 2015/11/02 21:04
갓 파이썬.... - 강승윤, 2016/07/07 19:46
def to_pathole(s):
    res=''
    for c in s:
        if c.isupper():c='_'+c.lower()
        elif c.isdigit():c='_'+c
        res += c
    return res

print to_pathole('codingDojang')
print to_pathole('numGoat30')

2016/01/24 22:07

상파

파이썬입니다.

def do(l):
    a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    return "".join(["_" + c.lower() if c in a else c for c in l])

print(do('numGoat30'))

2016/03/22 19:08

룰루랄라

단 3줄에 끝내다니 대단하시네요. - 최승호, 2016/07/15 00:01
이 아이디어 좋네요^^ - 디디, 2016/10/18 22:38
+1 `A if CONDITION else B`는 파이썬의 3항 연산자 대응표기입니다. 그러니 `("_"+c.lower() if c in a else c) for c in l` 로 이해하시면 됩니다. - 룰루랄라, 2016/10/27 18:49
저렇게 하면 한 if로 쓸 수 있군요 아이디어 좋내요 :D - soleaf, 2017/04/10 12:52
import re

change = lambda src: re.sub("([A-Z0-9])", lambda m:"_"+m.group().lower(), src)

print(change("codingDojang"))  # coding_dojang
print(change("numGoat30"))     # num_goat_3_0

2016/01/03 16:25

한정민

def camel_to_pothole(camel):
        pothole = ""
        for ch in camel:
                if ch.isupper():
                        pothole = pothole + "_" + ch.lower()
                elif ch.isdigit():
                        pothole = pothole + "_" + ch
                else:
                        pothole = pothole + ch

        return pothole

2015/06/22 15:26

Jethro

static void Main(string[] args)
        {
            string input = Console.ReadLine();
            StringBuilder answer = new StringBuilder();

            for (int i = 0; i < input.Length; i++)
            {
                string bigyo = input.Substring(i, 1);

                if (bigyo == bigyo.ToUpper() || IsNumeric(bigyo) == true)
                {
                    answer.Append("_" + bigyo.ToLower());
                }
                else
                {
                    answer.Append(bigyo);
                }

                Console.WriteLine(answer.ToString());
            }

        }

        static bool IsNumeric(string Tst)
        {
            int result = 0;
            return int.TryParse(Tst, out result);
        }

2015/06/24 00:30

허 빈

자바로 풀어봤습니다.

package codingDoJang;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ConvertCamelToPothole {
    public static void main(String[] args) {

        // Case 1
        String input = "codingDojang";

        // Case 2
        /*String input = "numGoat30";*/

        System.out.println("before  : " + input);

        String result = convert(input);

        System.out.println("After   : " +  result);
    }

    public static String convert(String input) {

        // 1. 대문자를 소문자로 바꾸고 앞 글자에 '_' 추가
        int inputSize = input.length();

        for (int i = 0 ; i < inputSize ; i++) {
            if (Character.isUpperCase(input.charAt(i))) {
                String str = String.valueOf(input.charAt(i));
                input = input.replace(str, "_" + str.toLowerCase()); 
            }
        }

        // 2. 숫자 앞에 '_' 추가
        Pattern p = Pattern.compile("\\d");
        Matcher m = p.matcher(input);

        while (m.find()) 
            input = input.replace(m.group(0), "_" + m.group(0));

        return input;
    }
}

2015/08/25 17:58

이 준균

private static String replacePotholeCase(String words) {
        String replace = null;
        for(char word : words.toCharArray()) {
            if(Character.isUpperCase(word) || Character.isDigit(word)) {
                replace = words.replace(String.valueOf(word), "_" + String.valueOf(word).toLowerCase());
            }
            if(replace != null) words = replace;
        }
        return words;
    }

2015/10/23 18:09

전 수현

$str = "numGoat30";
$keywords = preg_replace_callback("/[A-Z0-9]/",'change',$str);
function change($matches) {
    return "_".strtolower($matches[0]);
}
echo $keywords;

2016/01/08 10:19

물빛미르

파이썬 3.6 입니다

def change_case(s):
    for ch in s[1:]:    # 첫 번째 대문자는 무시
        if ch.isupper() or ch.isnumeric():
            s = s.replace(ch, f"_{ch.lower()}")
    return s

print(change_case('numGoat30'))

2019/12/03 11:51

vkospi

VB.NET

    Sub Main()
        Dim input As String = Console.ReadLine
        Dim r As New Text.StringBuilder

        For i As Integer = 0 To input.Length - 1
            Dim p As String = input.Substring(i, 1)

            r.Append({"_", ""}(CInt(p.ToUpper = p Or IsNumeric(p)) + 1) & p.ToLower)
        Next

        Console.WriteLine("Result: {0}", r.ToString)

        Console.ReadLine()
    End Sub

2015/06/21 20:12

Steal

Common Lisp 시도입니다.

(defun camel-to-pothole (string)
  (let ((buffer))
    (mapcar (lambda (ch)
              (if (or (upper-case-p ch) (digit-char-p ch))
                  (progn
                    (push #\_ buffer)
                    (push (char-downcase ch) buffer))
                  (push ch buffer)))
            (coerce string 'list))
    (coerce (reverse buffer) 'string)))

2015/06/22 23:15

꽃샘더위

            string input = Console.ReadLine();

            foreach(char c in input)
                if (c.ToString().Equals(c.ToString().ToUpper()))
                    input = input.Replace(c.ToString(), "_" + c.ToString().ToLower());

            Console.WriteLine(input);

2015/06/27 06:39

Raye

파이썬입니다.

import re

print re.sub([A-Z0-9])", "_\\\\1", 'codingDoJang')

print re.sub([A-Z0-9])", "_\\\\1", 'numGoat30')

2015/07/02 08:42

Kwon Sungdae

Ruby를 써봤습니다.

class Camel_to_Pothole
    def get_str
       puts Input_String: @myStr = gets
    end
    def change
       #Check the argument is exist.
       if @myStr == nil
           raise ArgumentError "No Argument"
           process.exit!(True)
       end

       #Delete spaces
       @myStr.chomp

       #Put '_' between patterns and downcase
       @myStr.gsub!(/[A-Z0-9]/){'_'+$&}.downcase!
    end
    def show
        print @myStr
    end
end

#Test
c2p = Camel_to_Pothole.new
c2p.get_str
c2p.change
c2p.show

2015/07/19 22:37

홍옥

c입니다.

void exce90()
{
    char str[255];
    int indx = 0;
    int gap = 'a' - 'A';
    int len;

    gets_s(str);
    len = strlen(str);

    if (str[0] <= 'Z' && str[0] >= 'A')
        str[0] += gap;

    for (int i = 0; i < len; i++)
    {
        if (str[i] <= 'Z' && str[i] >= 'A')
        {
            for (int j = len; j > i; j--)
            {
                str[j] = str[j - 1];
            }

            str[i + 1] = str[i] + gap;
            str[i] = '_';
            len++;
        }
        else if (str[i] >= '0' && str[i] <= '9')
        {
            for (int j = len; j > i; j--)
            {
                str[j] = str[j - 1];
            }
            str[i] = '_';
            len++;
            i++;
        }
    } 

    str[len] = '\0';
    printf("%s", str);
}

2015/08/12 09:18

조서현

def camelcase_2_potholecas(m):
    v = [ x.lower() if i == 0 else "_%s" % x.lower() if x.isupper() or x.isdigit() else x.lower() for i, x in enumerate(m) ]
    return "".join(v)

print camelcase_2_potholecas('codingDojang')
print camelcase_2_potholecas('numGoat30')

2015/08/13 15:10

BaekSeungWoo

def convert(input: String): String = {
    val regex = "([A-Z0-9])".r
    input.foldLeft("") {
        case (result, regex(c)) => result + s"_${c.toLower}"
        case (result, c) => result + c
    }
}

println(convert("codingDojang"))
println(convert("numGoat30"))

scala 입니다.

2015/08/21 15:43

killbirds

C#에 정규식 사용했습니다.

        private string replace(string test)
        {
            return Regex.Replace(test, @"[A-Z0-9]", delegate(Match match)
            {
                return "_" + char.ToLower(match.ToString()[0]);
            });
        }

2015/09/17 16:55

임 정구

public static String caseSwap(String str){

        //대문자 65 ~ 90
        //소문자 97 ~ 122
        StringBuffer sb = new StringBuffer();

        char[] ch = str.toCharArray();
        int i=0;

        while(i<ch.length){
            char temp = ch[i];

            // 대문자
            if(ch[i]>=65 && ch[i]<=90){
                sb.append('_');
                ch[i]+=32;
            } 

            // 정수
            if(ch[i]>=48 && ch[i]<=57){
                sb.append('_');
            }

            sb.append(ch[i]);
            i++;
        }

        return sb.toString();
    }

2015/09/17 17:31

임 찬혁

javascript

var toPotholeCase = function(camelCase) {

    var potholeCase = '';

    for (var i=0; i<camelCase.length; i++) {

        var ch = camelCase[i],
            upperCh = ch.toUpperCase();

        if (ch === upperCh)
            ch = "_" + ch.toLowerCase();

        potholeCase += ch;
    }

    return potholeCase;
};

//test
var test = "codingDojang numGoat30".split(' ');
for (var i in test)
    console.log(toPotholeCase(test[i]));

2015/09/22 13:58

배 경근

import re

def convertCtoP(case):
    ret_case = ''
    for c in case:
        if c.isupper() :
            ret_case += '_'
            c = c.lower()
        if c.isdigit():
            ret_case += '_'
        ret_case += c
    return ret_case


print(convertCtoP2("codingDojang30"))

2015/11/01 17:57

김 매미

파이썬입니다.

def camel_to_pothole(camel):
    pothole = ""
    for c in camel:
        if c.isupper():
            pothole += ("_" + c.lower())
        elif c.isdigit():
            pothole += ("_" + c)
        else:
            pothole += c
    return pothole

print(camel_to_pothole("codingDojang"))
print(camel_to_pothole("numGoat30"))

2015/11/05 11:33

김경호

파이썬 2.7

import string

s = 'numGoat30'

result = ''
for i in range(len(s)):
    if s[i] in string.uppercase or s[i] in string.digits:
        result  += '_'+s[i].lower()
    else:
        result += s[i]

print result

2015/12/29 19:43

hana11

파이썬이 string 특징을 이용해서 풀어봤습니다.

line = "numGoat30"

new_line = [x * (not 'A' <= x <= 'Z') * (not '0' <= x <= '9')
            + ('_' + x.lower()) * ('A' <= x <= 'Z')
            + ('_' + x) * ('0' <= x <= '9') for x in list(line)]

print(line + '  ->  ' + ''.join(new_line))

2015/12/31 11:50

SPJung

import re

pc = lambda src: re.sub("([A-Z0-9])", lambda m:"_"+m.group().lower(), src)

print(pc("codingDojang")) # coding_dojang print(pc("numGoat30")) # num_goat_3_0

2016/01/09 18:33

Hitz

  • python으로 작성하였습니다.
def camelToPothole(s):
    l=list(s)
    pos=[]
    for idx,c in enumerate(l):
        if c.isdigit() or c.isupper():
            pos.append(idx)

    for i in reversed(pos):
        if l[i].isupper():
            l[i]=l[i].lower()
        l.insert(i,'_')
    return "".join(str(c) for c in l)

camel="codingDojang"
camel2="numGoat30"
print camelToPothole(camel)
print camelToPothole(camel2)      

2016/01/11 09:58

씨니컬우기님

def camelcase(input1):
    new_list=[]
    digit_list=['0','1','2','3','4','5','6','7','8','9']
    for i in list(input1):
         if i.isupper()==True:
             new_list.append("_")
             new_list.append(i.lower())

         elif i in digit_list:
             new_list.append("_")
             new_list.append(i)
         else :
             new_list.append(i)

    return "".join(new_list)

input1 = "numGoat30"
print camelcase(input1)

2016/02/04 04:57

UNIST_BA

Ruby

두 가지로 풀어 봄.

# 방법 1 : gsub
to_pathole = ->camel { camel.gsub(/([A-Z0-9])/,'_\1').downcase }
# 방법 2 : reduce
to_pathole = ->s {s.chars.reduce([]) {|a,e| a<<(e==e.upcase ? "_"+e.downcase : e)}*''}

Test

expect(to_pathole["codingDojang"]).to eq "coding_dojang"
expect(to_pathole["numGoat30"]).to eq "num_goat_3_0"

2016/02/25 13:04

rk

swift 2.x

func camelToPothle(name : String) -> String{

        var result : String = String()
        for ch in name.characters {

            let num = String(ch).utf8.map{Int($0)}[0]
            if(num >= 65 && num <= (65+26)){
                result.appendContentsOf(String("_"))
                result.appendContentsOf(String(ch).lowercaseString)
            }
            else if(num >= 48 && num <= (48+10))
            {
                result.appendContentsOf(String("_"))
                result.appendContentsOf(String(ch).lowercaseString)
            }
            else
            {
               result.append(ch)
            }

        }

        return result
    }

2016/02/28 16:44

A = list(chr(x) for x in range(65, 91));N = list(str(x) for x in range(0,10))
while __name__ == '__main__':
    inpt = input('입력: ')
    print(''.join(list('_'+x.lower() if x in A else ('_' + x if x in N else x) for x in inpt)))

정규식 안쓰고 짧게 해봤습니다. 파이썬 3.5.1

2016/03/15 22:24

Flair Sizz

void changeCamelCase(String s) {
        StringBuilder builder = new StringBuilder();

        for(int i=0; i<s.length(); i++) {
            if(s.charAt(i) >='A' && s.charAt(i) <= 'Z' || (s.charAt(i) >='0' && s.charAt(i) <= '9')) {
                builder.append("_");
            }
            builder.append(s.charAt(i));
        }
        System.out.println(builder);
    }

java

2016/03/17 02:38

mozzi

파이썬입니다. 가급적 정규식을 안 쓰려고 했는데, 앞의 분이 isupper와 isdigit을 사용하셨네요. 멋지십니다.

import re
def chg(s):
    s_ = ''
    _s = list(s) #['c', 'o', 'd', 'i', ...] list반환
    for x in _s:
        if re.match('[A-Z]', x): #대문자이면
            s_ += '_' + x.lower()
            continue
        if re.match('\d', x):
            s_ += '_' + x
            continue
        s_ += x
    return s_

print(chg('codingDojang'))
print(chg('numGoat30'))

2016/03/18 23:20

디디

public String toPotholeCase(String variable){
        StringBuffer sb= new StringBuffer(variable);
       for(int i =  0 ; i <  sb.length() ;i++){
            if(isUpper(sb.charAt(i))) {
                sb.replace(i,i+1, toLower(sb.charAt(i))+"");
                sb.insert(i, '_');

            }else if(isNumeric(sb.charAt(i))){
                sb.insert(i,'_');
                i++;
            }
        }

        return sb.toString();

    }
    public boolean isUpper(char ch){
        return ((ch >='A' && ch <='Z') ? true : false);
    }
    public boolean isNumeric(char ch){
        return((ch >='0' && ch <='9')? true: false);
    }
    public char toLower(char ch){
        return (char)(ch - 'A'+'a');
    }

2016/04/12 21:07

xeo

patho="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
a="codingDojang"
b="numGoat30"

def pothole(a):
    aa=[]
    if a[0] in patho:
        aa=[a[0]]
        for i in a[1:]:
            if i in patho:
                aa.append("_"+i.swapcase())
            else:
                aa.append(i)
    else:
        for i in a:
            if i in patho:
                aa.append("_"+i.swapcase())
            else:
                aa.append(i)
    s=""
    for i in aa:
       s=s+i
    return s
print(pothole(a))
print(pothole(b))

2016/04/23 22:06

Dr.Choi

Python

import re

changePothole2 = lambda src: re.sub("([A-Z0-9])", lambda m:"_" + m.group().lower(), src)

def changePothole(name):
    _name = "" 

    if not type(name) is str:
        raise TypeError("Parameter is only str")

    for j in range(0, len(name)):
        if name[j].isupper():
            _name += "_" + name[j].lower()
        elif name[j].isdigit():
            _name += "_" + name[j]
        else:
            _name += name[j] 

    return _name

print(changePothole("codingDojang"))
print(changePothole("numGoat30"))
print(changePothole2("codingDojang"))
print(changePothole2("numGoat30"))

2016/04/27 16:04

SanghoSeo

>>> import re
>>> pc = lambda src: re.sub(r"([A-Z0-9])", r"_\1", src).lower()
>>> pc('numGoat30')
'num_goat_3_0'

2016/05/04 22:27

Park Ohyoung

Python

import  re

def to_pathole(text):
    modified = re.sub('[0-9A-Z]', lambda match_object: '_'+match_object.group().lower(), text)

    return modified

print (to_pathole("codingDojang"))
print (to_pathole("numGoat30"))

2016/05/27 23:38

Park Byunglim

https://docs.python.org/2/library/re.html 페이지에서 re.sub 함수 설명에서 두번째 인자를 함수로 받을 때 어떻게 작동하는지 설명 되어 있습니다. - Park Byunglim, 2016/05/27 23:41

C#으로 작성했습니다.

public string ConvertToPotholeCase(string input)
{
var output = string.Empty;
for (int i = 0; i < input.Length; i++)
{
var curr = input[i];
if (char.IsNumber(curr) || char.IsUpper(curr)) output += "_";
output += curr.ToString().ToLower();
}
return output;
}

2016/06/02 22:47

Straß Böhm Jäger

자바입니다. 뭔가 노가다한것같은 기분이 ...... ㅠ

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CamelCase를Pothole_case로바꾸기 {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        String input = scan.nextLine();

        List<String> strList = new ArrayList<>();

        for(int i=0; i<input.length(); i++) {
            char c = input.charAt(i);
            if(isUpperCase(c) || isDecimal(c)) {
                strList.add("_"+(isUpperCase(c) ? String.valueOf(c).toLowerCase() : c));
                continue;
            }
            strList.add(String.valueOf(c));
        }

        for(String s : strList) System.out.print(s);
    }

    public static boolean isUpperCase(char c) {
        int toInteger = c;

        if(65 <= toInteger && toInteger <= 90) return true;
        else return false;
    }

    public static boolean isDecimal(char c) {
        int toInteger = c;

        if(48 <= toInteger && toInteger <= 57) return true;
        else return false;
    }
}

2016/07/07 19:43

강승윤

camel=input('CamelCase : ')
k=0
while k!=len(camel):
    if k==0:
        camel=camel[0].lower()+camel[1:]
        k+=1
    elif camel[k].isupper()==True:
        camel=camel[:k]+'_'+camel[k].lower()+camel[k+1:]
        k+=2
    else:
        k+=1

print(camel)

숫자인 경우는 적용하지 못했습니다.

2016/07/14 23:43

최승호

자바 로 코딩

    public static void main(String[] args){

        try{

            StringBuffer sb = new StringBuffer();

            String str = "codingDojang30";

            char[] ch = str.toCharArray();

            for(int i=0; i<ch.length; i++){

                Character chVal = ch[i];

                if( Character.isUpperCase(chVal) || Character.isDigit(chVal) ){
                    sb.append("_").append(Character.toLowerCase(chVal));
                }else{
                    sb.append(chVal);
                }
            }

            System.out.println(sb.toString());

2016/07/21 10:30

황 정석

public static void main(String[] args) {
        String str="codingDojang";
        String result;
        Pattern p = Pattern.compile("[A-Z]");
        Matcher m =p.matcher(str);
            while(m.find())
            {
                result= str.replaceFirst(m.group(),"_"+m.group());
                System.out.println(result);
            }

    }

2016/07/26 14:30

Oh Tae Gyeoung

정규식이 바로떠올라서 정규식으로 해봤습니다! - Oh Tae Gyeoung, 2016/07/26 14:30
strEx = input('문자열을 입력하세요. : ')
strFinal = ''

for one in strEx :
        if one.upper() == one :
                strFinal = strFinal + '_' + one.lower()
        else :
                strFinal = strFinal + one


print(strFinal)

2016/08/30 15:08

박창석

ASCII code를 이용해서 바꿔봤습니다.

def makePothole(input):
    orgString = ""
    for i in str(input):        
        if ord(i) > 64 and ord(i) < 91:
            orgString += "_" + i.lower()
        elif ord(i) > 47 and ord(i) < 58:
            orgString += "_" + i
        else:
            orgString += i

    return orgString

print(makePothole('codingDojang'))
print(makePothole('numGoat30'))

2016/09/05 13:56

Kim Sean

python

def Camelcase_to_Pothole_case(s):
    st=""
    for i in s:
        if i.isupper():
            i="_"+i
        elif i.isdigit():
            i="_"+i
        st+=i
    print st

Camelcase_to_Pothole_case("codingDojang")

2016/09/06 15:52

leye195

#define _CRT_SECURE_NO_WARNINGS

#include <windows.h>
#include <stdio.h>

#define STR_LEN 256


int main(void) {
    char str[STR_LEN];
    //codingDojang ,, numGoat30 input
    printf("Input : ");
    gets_s(str);
    char rst[STR_LEN];
    int len = 0 ;
    for (int i = 0; i < strlen(str); i++) {
        if (isupper(str[i])) {
            rst[len++] = '_';
            rst[len] = tolower(str[i]);
        }
        else if (isdigit(str[i])) {
            rst[len++] = '_';
            rst[len] = str[i];
        }
        else {
            rst[len] = str[i];
        }
        len++;
    }
    rst[len] = '\0';
    printf("%s -> %s", str, rst);
    system("pause");
    return 0;
}

2016/09/22 17:05

개허접

def pothole_case(n):
    result=""
    for k in n:
        if k == k.upper():
            result+="_"+k.lower()
        elif k == k.lower():
            result+=k
        else:
            result+=k
    return result

print (pothole_case("thisIsACamelCaseString"))

2016/10/11 14:13

Kennen

파이썬

def transPathole(strCamele):
    strPathole = ''
    for i in strCamele:
        if i.isupper():
            i = '_' + i.lower()
        if i.isdigit():
            i = '_' + i
        strPathole += i

    return(strPathole)

print(transPathole('codingDojang'))
print(transPathole('numGoat30'))

2016/10/17 09:50

훠니

Java

import java.util.function.Function;
import java.util.stream.Collectors;

public class CameleToPothole {
    public static void main(String[] args) {
        Function<String, String> cameleToPothole = s ->
                s.chars().mapToObj(c -> (char)c).map(letter -> Character.isUpperCase(letter) ?
                        "_"+Character.toLowerCase(letter):Character.toString(letter))
                        .collect(Collectors.joining());
        System.out.println(cameleToPothole.apply("cameleToPothole"));
    }
}

결과

camele_to_pothole

2016/10/19 23:20

compert

Python 코드입니다. 입력값이 소문자면 출력값에 그대로 더하고, 그외는 언더바를 하나 추가한 후 소문자로 만들어서 더해줬습니다.

in_str = input("CameleCase: ")

out_str = ""
small = 'abcdefghijklmnopqrstuvwxyz'

for i in in_str:
    if i in small:
        out_str += i
    else:
        out_str += '_'
        out_str += i.lower()

print(a)

파이썬 초보입니다. 많은 피드백 부탁드립니다!

2016/10/20 21:22

조 우성

안녕하세요. C++로 풀어봤습니다. 예시에 대문자로 시작하는 경우가 없는거 같아서 일단 무조건 소문자로 시작하는 전제로 풀었습니다.

#include<iostream>
#include<string>
using namespace std;

int setSign(int num)
{
    if(num > 96 && num <123)//소문자
        return -1;
    else if(num > 64 && num <91)//대문자
        return 1;
    else
        return 0;
}

void main()
{
    cout<<"Hello Stranger??"<<endl;

    string str;
    string res = "";

    cout<<"문자열을 입력하시오"<<endl;
    cin>>str;

    for(int i=0; i<str.length(); i++)
    {
        if(setSign((int)str[i]) == 1)
        {
            str[i] = (char)((int)str[i] + 32);
            res = res+'_';
        }
        else if(setSign((int)str[i]) == 0)
        {
            res = res+'_';
        }
        res = res + str[i]; 
    }
    cout<<res;
}


2016/11/01 22:46

이재웅

public static void main(String[] args) { String text = "numGoat30"; String newText = ""; int increaseNumber = 0;

    for(int i = 0; i < text.length(); i++) {
        if(Character.isUpperCase(text.charAt(i)) || (text.charAt(i) >= 48 && text.charAt(i) <= 57)) {
            if(newText.equals("")) {
                newText = text.substring(0, i) + "_" + Character.toString(text.charAt(i)).toLowerCase() + text.substring(i + 1);
            }
            else {
                newText = newText.substring(0, i + increaseNumber) + "_" + Character.toString(text.charAt(i)).toLowerCase() + text.substring(i + 1);
            }
            increaseNumber++;
        }
    }
    System.out.println(newText);
}

2016/11/04 18:47

박요한

import re
def to_pothole_case(arg):
    return re.sub(r'((?<!^)(?<!_))([A-Z0-9])', r'_\2', arg).lower()

Python 3.5.2에서 작성하였습니다.

2016/11/23 09:35

Yeo HyungGoo

자바로 작성했습니다.

public String PotholecaseParser(String input){

        String strResult = "";

        for(int i =0; i< input.length(); i++){

            if((input.charAt(i) >= 65 && input.charAt(i) <= 90) || (input.charAt(i) >= 48 && input.charAt(i) <= 57)){

                strResult += "_";

            }
            strResult += input.charAt(i);

        }

        strResult = strResult.toLowerCase();

        return strResult;
    }

2016/11/24 23:26

francis

def changePothole(st):
    new_s = ''
    for i,s in enumerate(st):
        if ord(s) >= 65 and ord(s) <= 90:
            new_s = new_s + '_' + chr(ord(s)+32)
        elif ord(s) >= 48 and ord(s) <= 57:
            new_s = new_s + '_' + s
        else:
            new_s = new_s + s
    return new_s

print(changePothole('numGoat30'))

2016/11/28 18:07

바바

아직 눕눕이라...

f = "CodingDojang"

for i in f[1:]: #첫번째는 안건든다 생각하고...
    if i.isupper or i.isdigit():
        f = f.replace(i, '_' + i)

new_f = f.lower()
print(new_f)

2016/12/04 07:31

Kim Soojong

string,result = input(),str()
for x in string:
    if x.isupper() or x.isnumeric():
        result += '_' + x.lower()
    else:
        result += x
print(result)

#### 2016.12.12 D- 437 ####

2016/12/12 22:58

GunBang

C(11) gcc v4.9.4

//79COLUMNS////////////////////////////////////////////////////////////////////
// CamelCase를 Pothole case로 바꾸기
#include <stdio.h>
#include <ctype.h>
#include <string.h>

#define MAX_WORD_LEN 80 // 한단어의 최대길이

// 주요함수
static char *to_pothole(const char *str);
// 문자열 헬퍼 함수
inline static void line_clear(void) { while (getchar() != '\n') continue; }
static char* s_gets(char* line, int length);

int main(void)
{
    char temp[MAX_WORD_LEN]; 
    while (s_gets(temp, MAX_WORD_LEN))
    {
        strcpy(temp, to_pothole(temp));
        puts(temp);
    }

    return 0;
}

char *to_pothole(const char *str)
{
    static char temp[MAX_WORD_LEN];
    int cursor = 0;

    while (*str)
    {
        if (isupper(str[cursor])) // 첫글자 대문자는 소문자로 변경
        {
            temp[cursor++] = tolower(*str++);
            continue;
        }

        if (isupper(*str) || isdigit(*str)) // 대문자, 숫자는 _문자로 변경
        {
            temp[cursor++] = '_';
            if (cursor == MAX_WORD_LEN - 1) // 단어길이 제한을 넘어갈수있다
                break;
            temp[cursor++] = tolower(*str++);
        }

        else
            temp[cursor++] = *str++;

        if (cursor == MAX_WORD_LEN - 1) // 단어길이제한을 지키자
            break;

    }
    temp[cursor] = '\0'; // 중요하다

    return temp;
}

static char* s_gets(char* line, int length)
{
    char* ret;
    char* find;

    ret = fgets(line, length, stdin);
    if (ret)    // ret != NULL
    {
        find = strchr(line, '\n');
        if (find)   // find != NULL
            *find = '\0';
        else    // find == '\0'
            line_clear();
    }

    return ret;
}

2016/12/29 14:00

디디

def Pothole_case(name):
    name=list(name)
    case=[]
    case+=[name[0].lower()]
    name=name[1:]
    while name!=[]:
        if name[0].upper()==name[0]:
            case+=[name[0].lower()]
        else:
            case[-1]+=name[0]
        if len(name)>1:
            name=name[1:]
        elif len(name)==1:
            name=[]
    print("_".join(case))

2017/02/14 00:20

김구경

Python


def camelToPothole(inputString):
    Pothole =''
    for letter in inputString:
        if letter.islower():
            Pothole =Pothole + letter
        else:
            Pothole =Pothole + "_" +letter.lower()
    return Pothole

2017/02/15 15:34

오준균

/*

dev : peanutBro

date : 170217

content : 
Example:

codingDojang--> coding_dojang

numGoat30--> num_goat_3_0

위 보기와 같이 CameleCase를 Pothole_case 로 바꾸는 함수를 만들어요!

출처: UT past test

*/

#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

#include <iostream>
#include <string>
using namespace std;

void editStr(string);

int main(void)
{
    string str1 = "codingDojang", str2 = "numGoat30";

    editStr(str1);
    editStr(str2);
}

void editStr(string str)
{
    for (int i = 0; i < str.length(); i++)
    {
        if (str[i] >= 'A' && str[i] <= 'Z')
        {

            string temp = "_";
            char* tempStr = new char[temp.length() + 1];
            strcpy(tempStr, temp.c_str());
            tempStr[temp.length()] = str[i] - 'A' + 'a';
            tempStr[temp.length() + 1] = '\0';
            temp = tempStr;
            str.replace(i, 1, temp);
            i++;
        }
        else if (str[i] >= '0' && str[i] <= '9')
        {
            string temp = "_";
            char* tempStr = new char[temp.length() + 1];
            strcpy(tempStr, temp.c_str());
            tempStr[temp.length()] = str[i];
            tempStr[temp.length() + 1] = '\0';
            temp = tempStr;
            str.replace(i, 1, temp);
            i++;
        }
    }

    cout << str << endl;
}

2017/02/18 00:53

강병구 (peanutBro)

str1 = "codingDojang"
str2 = "numGoat30"
pothole = ""

for char in str1:
    if char.islower():
        pothole += char
    else:
        char = char.lower()
        pothole = pothole + "_" + char

print(pothole)

2017/02/22 00:48

Scott.Jun

c언어로 해봤습니다.


#include<stdio.h>
#include<stdlib.h>
/*Pothole_case로 변환합니다.*/
char* change(char * sentence) {
    int length = pothole_length(sentence);
    char* new_sentence = (char*)malloc(sizeof(char) * (length+1));

    for (int i = 0, j = 0; i < strlen(sentence); i++) {
        switch (what_is_this(*(sentence+i))) {
        case 0:
            *(new_sentence + i + j) = *(sentence + i);
            break;
        case 1:
            *(new_sentence + i + j) = '_'; j++;
            *(new_sentence + i + j) = *(sentence + i) + 32;
            break;
        case 2:
            *(new_sentence + i + j) = '_'; j++;
            *(new_sentence + i + j) = *(sentence + i);
            break;
        }
    }
    new_sentence[length] = '\0';
    return new_sentence;
}

/*CamelCase를 변활할 때 미리 char*을 만들기위해 Pothole_case를 만들때 쓰일 
배열의 크기를 계산합니다.*/
int pothole_length(char* sentence) {
    int length = 0;
    for (int i = 0; i < strlen(sentence); i++) {
        if (*(sentence + i) >= 'a' & *(sentence + i) <= 'z')
            length += 1;
        else
            length += 2;
    }
    return length;
}

/*한 글자씩 읽어와 소문자 대문자 그외 문자를 판별합니다.*/
int what_is_this(char a) {
    if (a >= 'a' & a <= 'z')
        return 0;
    else if (a >= 'A' & a <= 'Z')
        return 1;
    else
        return 2;
}

int main() {
    char* sentence = "numGoat30";
    sentence = change(sentence);
    printf("%s", sentence);
    free(sentence);
    return 0;
}

2017/03/04 21:49

KimSeonbin

  • python 3.5.2
def to_pothole(s) :
    c='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    n='0123456789'
    res = ''
    for x in s :
        if x in c :
            res=res+'_'+x.lower()
        elif x in n :
            res=res+'_'+x
        else :
            res=res+x
    return res

2017/03/06 21:00

강정민

String input ="numGoat30";
        String output = "";
        char [] arrCh = input.toCharArray();

        for (char c : arrCh) {
            if(Character.isUpperCase(c)|| Character.isDigit(c)){
                String o = Character.toString(c);
                output += "_" + o.toLowerCase();
            }else{
                output += c;
            }
        }
        System.out.println(output);

2017/03/07 17:19

박재형

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.lang.System.in;

public class PotholeCase {

    public static void main(String[] args) {
        Pattern p = Pattern.compile("[A-Z,0-9]");
        Matcher m = p.matcher(new Scanner(in).next());
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            m.appendReplacement(sb, "_" + m.group().toLowerCase());
        }
        m.appendTail(sb);
        System.out.println(sb.toString());
    }
}

2017/03/11 19:18

genius.choi

camel = "codingDojang"

def Pothole(cam):
    x = sorted(cam)[0]
    return cam.replace(x, "_" + x.lower())

Pothole(camel)

2017/03/15 09:49

ken choi

def main(string):
    result = list()

    for i in string:
        if i.isupper():
            result.append("_")
            result.append(i.lower())
        elif i.isdigit():
            result.append("_")
            result.append(i)
        else:
            result.append(i)

    return "".join(result)


if __name__ == '__main__':
    string = "codingDojang"
    res = main(string)

    print(res)

2017/03/29 17:45

jkkim

package training;

import java.util.Scanner;

public class ConvPotholeCase {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Please insert Sample String? ");
        String strTxt = sc.next();

        StringBuffer sb = new StringBuffer();

        char ch;

        for(int i=0;i<strTxt.length();i++){
            ch = strTxt.charAt(i);
            if(Character.isDigit(ch)){
                sb.append("_"+ch);
            } else if(Character.isUpperCase(ch)){
                sb.append("_"+String.valueOf(ch).toLowerCase());
            } else {
                sb.append(ch);
            }
        }
        System.out.println("Convert ==> " + sb);
    }
}

2017/03/31 16:44

acedo

def Cam2Poth(word):
    new = ""
    for i in word:
        if (ord(i) >= 65 and ord(i) <= 90):
            new += "_"
            new += i.lower()
        elif (ord(i) >= 48 and ord(i) <= 57):
            new += "_"
            new += i
        else:
            new += i
    print(new)


Cam2Poth("codingDojang")
Cam2Poth("numGoat30")
Cam2Poth("kyohoonSim0211")

python 3.5입니다. 함수의 입력으로 들어온 문자열의 문자 하나하나를 일단 판단했습니다. 이때 아스키코드값을 활용해서 ('A' = 65, 'Z' = 90, '0' = 48, '9' = 57), 대문자면 앞에 _ 를 추가하고 소문자로 바꿔주고 0~9이면 앞에 _를 추가하도록 코딩했습니다.

결과적으로 coding_dojang num_goat_3_0 kyohoon_sim_0_2_1_1 이 출력되었습니다.

2017/04/06 21:26

simkyohoon

private static String toPothole(String contents){
        StringBuffer pothole  = new StringBuffer();
        for(int i=0; i<contents.length(); i++){
            char c = contents.charAt(i);
            if(c >= 'A' && c <= 'Z'){
                pothole.append('_').append(Character.toLowerCase(c));
            }else if(c >= '0' && c <= '9'){
                pothole.append('_').append(c);
            }else{
                pothole.append(c);  
            }

        }

        return pothole.toString();
    }

2017/04/06 21:32

yh

def changer(string):
    string= list(string)
    for i in range(len(string)):
        if (string[i] != string[i].lower()) or string[i].isdigit() : string[i] = '_%s' % string[i].lower()
    return ''.join(string)

print(changer('codingDojang'))
print(changer('numGoat30'))

2017/04/08 00:57

Park Jay

def camel_to_pothole(camel_str):
    arr = []
    for s in camel_str:
        if len(arr) == 0 :
            arr.append(s)
        elif 'A' <= s <= 'Z':
            arr.append('_' + s.lower())
        elif s.isnumeric():
            arr.append('_'+s)
        else:
            arr.append(s)
    return ''.join(arr)

print (camel_to_pothole('codingDojang'))
print (camel_to_pothole('numGoat30'))

2017/04/10 12:48

soleaf

import java.lang.*;
import java.util.*;
import java.io.*;

public class Main {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String inputString = new String();
        inputString = input.nextLine();
        int l = inputString.length();
        char[] inputCharArray = new char[l];
        inputCharArray = inputString.toCharArray();
        char[] buffer = new char[2];
        buffer[0] = buffer[1];
        buffer[1] = inputCharArray[0];
        for(int i=1;i<l;i++) {
            buffer[0] = buffer[1];
            buffer[1] = inputCharArray[i];
            if(Character.isUpperCase(buffer[1])) {
                System.out.print(Character.toString(buffer[0]));
                System.out.print("_"+Character.toString(Character.toLowerCase(buffer[1])));
                buffer[0] = buffer[1];
                buffer[1] = inputCharArray[i];
            }
            else if(Character.isUpperCase(buffer[0])) {
                if(i==1) {
                    System.out.print(Character.toString(Character.toLowerCase(buffer[0])));
                }
                else {
                    continue;
                }
            }
            else {
                System.out.print(Character.toString(buffer[0]));
            }
        }
        System.out.print(Character.toString(buffer[1]));
    }
}

2017/04/12 21:00

취미로재미로

ca=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
lo=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
num=['1','2','3','4','5','6','7','8','9','0']
a="codingDojang"
b="numGoat30"
for i in a:
    if i in ca:
        i=("_"+lo[ca.index(i)])
    if i in num:
        i=("_"+i)
    print(i,end="")

2017/04/18 13:12

조현

s=input()
result=''
for i in s:
    if i.isupper() or i.isnumeric:
        result+='_'+i.lower()
    else:
        result+=i
print(result)

2017/04/23 16:25

빅디펜스

result = CamelEx = input("Enter CamelCase : ")
for x in CamelEx[1:]:
    if x.isupper():
        y = '_'+ x.lower()
        result = result.replace(x,y)
    if x.isdigit():
        y = '_' + x
        result = result.replace(x,y)


2017/05/05 21:21

AJ

자바로 풀어봤습니다.

    String text = "sampleApple";

    Pattern p = Pattern.compile("[A-Z0-9]");
    Matcher m = p.matcher(text);

    while(m.find()) {
        text = text.replaceAll(m.group(), "_" + m.group().toLowerCase());
    }

    System.out.println(text);

```

2017/05/10 10:26

양민우

input_string = input("Input is: ")
output_string = ""

for character in input_string:
    if character.islower():
        output_string = output_string + character
    elif character.isupper():
        output_string = output_string + '_' + character.lower()
    else:
        output_string = output_string + '_' + character

print(output_string)

2017/05/15 16:46

Taewon Song

# cording = utf-8

a = input("입력하세요 : ")
r = ""

for c in a:
    if c.isupper() :
        r += "_"+c.lower()

    elif c.isdigit() :
        r += "_"+c

    else:
        r += c

print(r)

2017/05/18 17:14

최준호

public class CamelCase2Pothole_case {
    public static void main(String[] args) {
        String[] strs = {"codingDojang","numGoat30"};
        for(String str : strs){
            StringBuilder sb = new StringBuilder();
            for(char c : str.toCharArray()){
                if(Character.isUpperCase(c)|| Character.isDigit(c)){
                    sb.append('_');
                    sb.append(Character.toLowerCase(c));
                }else{
                    sb.append(c);
                }
            }
            System.out.println(str + " : " + sb.toString());
        }
    }
}

2017/06/02 18:20

김중운

import copy
def camtopot(string):
    stringlower = list(string.lower())
    string = list(string)
    stringresult = copy.deepcopy(stringlower)
    ilist = list()
    for i,x in enumerate(string):
        if x != stringlower[i]:
            ilist.append(i)
        elif 48 <= ord(x) <= 57:
            ilist.append(i)
    for i,x in enumerate(ilist):
        stringresult.insert(x,'_')
        for j in range(i+1,len(ilist)):
            ilist[j] += 1

다른분들에 비해 복잡하네요;

2017/06/04 13:43

S ReolSt

def fpothole(S):

c = -1
for s in S:
    c = c + 1
    for i in range(65, 91):
        if ord(s) == i:
            S = S.replace(s, chr(i+32))
            S = S[:c] + "_" + S[c:]
print(S)

2017/06/06 21:26

김순효

// 명명 방식 변경 - C#
using System;
namespace Camel_pot_hole
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter your CamelCase name...");
            string word = Console.ReadLine();
            string result = word;
            for (int i = 0; i < word.Length; i++)
                if (word[i] >= 'A' && word[i] <= 'Z')
                {
                    string a = "_"; a += (char)(word[i] + 32);
                    result = result.Replace(char.ToString(word[i]), a);
                }
                else if (word[i] >= '0' && word[i] <= '9')
                {
                    string a = "_"; a += (word[i]);
                    result = result.Replace(char.ToString(word[i]), a);
                }
            if (result[0] == '_')
                result = result.Remove(0, 1);
            Console.WriteLine(result);
        }
    }
}

2017/06/19 17:44

Jeong Hoon Lee

javascript

// regular expression 이용
// 첫 글자가 대문자인 경우 소문자로는 바꿔주나 _는 앞에 붙이지 말아야 한다.
// 따라서 첫 글자 처리는 따로 함
var pothole_case = function(camel) {
    return (camel[0] || "").toLowerCase() + camel.slice(1).replace(/([A-Z0-9])/g, (s => `_${s.toLowerCase()}`));
};

console.log(pothole_case("codingDojang"));
console.log(pothole_case("CodingDojang"));
console.log(pothole_case("numGoat30"));
console.log(pothole_case(""));

2017/06/19 23:15

funnystyle

문자열의 제일 앞은 적용하지 않았습니다.

def camelToPothole(s):
    retStr = ''
    for i, cur_char in enumerate(s):
        if i >= 1 and s[i-1].islower() and cur_char.isupper():
            retStr += '_' + cur_char.lower()
        elif i >= 1 and cur_char.isnumeric():
            retStr += '_' + cur_char
        else:
            retStr += cur_char
    return retStr

print(camelToPothole('numGoat30'))
print(camelToPothole('codingDojang'))
print(camelToPothole('123testAbc'))

2017/06/20 02:48

Ahn WooJin

c로 풀이

#include <stdio.h>
int main(void)
{
    char a[40];
    int i;
    printf("CameleCase 입력 : ");
    scanf("%s",a);
    printf("Pathole_case 출력 : ");
    for(i=0;a[i]!='\0';i++)
    {
        if(((a[i]>='A')&&(a[i]<='Z'))||((a[i]>='0')&&(a[i]<='9'))) printf("_");
        printf("%c",a[i]|32);
    }
    return 0;
}

2017/06/20 09:27

박동준

JAVA로 풀이

public static boolean isNumber(String str){

        boolean result = false;

        try{

            Double.parseDouble(str) ;

            result = true ;

        }catch(Exception e){}

        return result ;

    }


    public static void main(String[] args) {



        String a = "numGoat30" ; 
        String br = "" ;
        String changed = "";

        for (int i = 0 ; i < a.length(); i++)
        {


                char b = a.charAt(i);

                br = String.valueOf(b);




                if (br == br.toUpperCase()){

                    changed = changed + "_"+ br.toLowerCase() ;

                } else if(isNumber(br)) {

                    changed = changed + "_" + br ; 

                }else{

                    changed = changed + br ; 

                }


        }

        System.out.println(changed);

    }

2017/06/21 15:53

JIHooN KIM

import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        StringBuffer sb = new StringBuffer();

//      대문자 ASCII: 65~90
//      숫자 ASCII: 48~57
        int i = 0;
        int strLength = str.length();
        while (i < strLength) {
            char c = str.charAt(i);
            if ((c >= 65 && c <= 90) || (c >= 48 && c <= 57)) {
                sb.append("_");
            }

            if (c >= 65 && c <= 90) {
                sb.append((char) (c + 32)); //대문자를 소문자로 만들기
            } else {
                sb.append(c);
            }
            i++;
        }

        System.out.println(sb);
    }
}

2017/06/28 10:07

이호섭

코드

def is_upper(chr):
    return ('A' <= chr and chr <= 'Z')
def is_number(chr):
    return ('0' <= chr and chr <= '9')

def camel_case_to_pothole_case(camel_case):
    pothole_case = "";
    for i in range(len(camel_case)):
        if ( is_upper(camel_case[i]) ):
            pothole_case += ("_" + (camel_case[i].lower()))
        elif ( is_number(camel_case[i]) ):
            pothole_case += ("_" + (camel_case[i]))
        else:
            pothole_case += (camel_case[i])

    return pothole_case

2017/06/29 16:17

이정환

def convert(cameleCase):
    def _convert(ch):
        A = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        if ch in A: return '_' + ch.lower()      
        else:       return ch

    return cameleCase[0] + ''.join(map(_convert, cameleCase[1:]))

파이썬은 C에서 쓰던 ? 연산자가 없어서 많이 불편하네요.

str(['a','b','c']) --> '['a', 'b', 'c']' 이 되길래 찾아보니 ''.join(['a','b','c']) --> 'abc' 이런 식으로 쓰는군요.

궁금한게 if문이 들어가는 함수는 lambda로 처리가 불가능한지?

2017/07/03 10:05

Noname

+1 저도 최근에 Python을 공부했는데, 아래처럼 사용하시면 됩니다. convert = lambda ch: '_' + ch.lower() if ch in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' else ch C나 Java에서는 '조건식' ? '참값' : '거짓값' 형태의 3항 연산자를 제공하는데, Python에서는 '참값' '조건식' '거짓값' 형태로 사용하게 됩니다. Ex) True if a is 0 else False - SOUP, 2017/07/05 13:15

Python으로 작성해봤습니다.

def to_pothole_case(s):
    return ''.join(map(lambda x: '_' + x.lower() if x.isupper() or x.isdigit() else x, s)).lstrip('_')

2017/07/05 13:11

SOUP

    public static String convertToPothole_case(String str){
        StringBuilder result = new StringBuilder();
        for ( char c : str.toCharArray() ){
            if ( 'A' <= c && c <= 'Z' ) {
                result.append("_").append((char) (c + 32));
            }else{
                result.append(c);
            }
        }
        return result.toString();
    }

2017/07/06 10:44

요지

def PotholeCaseConverter(targetWord):
    capitalLetter = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] #대문자를 기준으로 단어가 분절된다. 
    number = ["0", "1","2", "3", "4", "5", "6", "7", "8", "9"] # 숫자 하나 마다 _로 구분 
    cutPointList = capitalLetter + number #이 문자들을 기준으로 나눌 것이기 때문에 cutPoint라고 명명하였다. 구분자들을 모두 모은 List 
    convertedResult = "" #최종 결과를 저장하는 Variable

    while True :
        capitalIndexList = []
        firstletter = targetWord[0]


#Camel Case라면 첫번째 문자를 소문자로 표기하지만, 대문자로 오기한 Case를 반영하였다 ex)'C'odingDojang
        if firstletter in cutPointList:  
            convertedResult = convertedResult + targetWord[0]
            targetWord = targetWord[1:]
        else:  #첫번째 문자를 소문자로 올바르게 입력한 Camel Case의 경우, pass! 
            pass

        for capital in cutPointList: #대문자, 숫자의 index를 List에 모두 취합하였다
            if targetWord.find(capital) != -1: 
                capitalIndexList.append(targetWord.find(capital))


        if capitalIndexList == []:
            convertedResult = convertedResult + targetWord
            break
        capitalIndexList.sort()
        cutPoint = capitalIndexList[0] #첫번째 cutPoint문자의 index 
        addition = targetWord[0:cutPoint]
        convertedResult = convertedResult + addition.rstrip() +"_"  #입력문자에 빈칸이 있는 경우를 고려하였다. 
        targetWord = targetWord[cutPoint:] #나머지부분은 다시 루프를 돌린다 find함수가 무조건 가장 첫번째 index만 알려주므로. 잘라서 계속 돌려야한다. 

    convertedResult = convertedResult.lower() 
    print(convertedResult) 

PotholeCaseConverter("")
PotholeCaseConverter("codingDojang")
PotholeCaseConverter("numGoat30")


안녕하세요! 저번주에 프로그래밍 처음 시작한 학생입니다. 직관적이고 짧고 간결한 코딩이 좋은 코딩이군요...ㅎㅎㅎ 풀이 눈팅 한번 해보고 부끄러워서 올릴까말까했는데..초보분들 제꺼 보고 힘내세욧!!:))

풀이방법 : 대문자,숫자의 인덱스를 찾아 슬라이싱을 통해 앞에서부터 짤라나갔습니다. numGoat30의 경우, num // num_Goat // num_Goat_3 // num_Goat_3_0 순서로 답을 구해나갔습니다.

첫번째 문자가 대문자일 경우, 단어 사이에 띄어쓰기가 있을 경우 모두 고려했습니다. 감사합니다.

2017/07/10 00:31

김용준

파이썬 3 시작한 지 3일밖에 안 돼서 많이 부족합니다

black_pink_in_your_area_1_6_0_8_0_8

a = 'blackPinkInYourArea160808'
alp = 'QWERTYUIOPASDFGHJKLZXCVBNM1234567890'
small = ['_'+b for b in alp.lower()] # alp에 있는 글자들 앞에 '_' 붙인 후 소문자로 바꾸고 리스트로
for  C, s in zip(alp, small): 
    a = a.replace(C, s) #alp에 있는 대문자와 숫자들을 small에 있는 앞에 '_'가 붙은 글자들로 대체

print(a)

2017/07/19 14:23

이재희

import java.util.*;

public class CamelCaseTo_pothole_case {
    public static String convert(String input) {
        char[] c = input.toCharArray();
        StringBuffer output = new StringBuffer();
        if('A'<=c[0] && c[0]<='Z') {
            output.append((char) (c[0]+32));
        }
        else {
            output.append(c[0]);
        }
        for(int i=1; i<input.length(); i++) {
            if('A'<=c[i] && c[i]<='Z') {
                output.append("_"+(char) (c[i]+32));
            }
            else if('0'<=c[i] && c[i] <='9') {
                output.append("_"+c[i]);
            }
            else {
                output.append(c[i]);
            }
        }
        return output.toString();
    }   
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String name = sc.nextLine();
        CamelCaseTo_pothole_case CaToPo = new CamelCaseTo_pothole_case();
        System.out.println(CaToPo.convert(name));
    }
}

2017/07/27 17:20

곽철이


public class Lv1 {

    public String func(String str){
        char[] arr = str.toCharArray();
        StringBuffer sb = new StringBuffer();
        for (char c : arr) {
            if(c >= 'A' && c <= 'Z'){
                c += 32;
                sb.append("_"+c);
            }
            else if(c >= '0' && c <= '9'){
                sb.append("_"+c);
            }
            else sb.append(c);
        }
        return sb.toString();
    }

    public static void main(String[] args){
        Lv1 obj = new Lv1();
        System.out.println(obj.func("codingDojang"));
        System.out.println(obj.func("numGoat30"));

    }
}

2017/07/31 17:33

sunga

public static void Pothole_case(){
        /*
         * Example:
         *codingDojang --> coding_dojang
         *numGoat30 --> num_goat_3_0
         *위 보기와 같이 CameleCase를 Pothole_case 로 바꾸는 함수를 만들어요!
         */ 
        String Camelcase;
        String Pothole_case[] ;

        Scanner scan = new Scanner(System.in);
        Camelcase = scan.nextLine();

        char []temp;
        temp = Camelcase.toCharArray();
        int k = temp.length;
        String temp2;
        Pothole_case =new String[k];
        String change="";
        for(int i = 0; i < k; i++){
            if(temp[i] >= 65 && temp[i] <=90){              
                temp[i] +=32;
                change=String.valueOf(temp[i]);
                temp2 = "_"+change;
                Pothole_case[i]=temp2;
            }
            else if(temp[i] >= 48 && temp[i] <=57){
                change=String.valueOf(temp[i]);
                temp2 = "_"+change;
                Pothole_case[i]=temp2;
            }
            else{
                change =String.valueOf(temp[i]);
                Pothole_case[i] = change;
            }

        }
        for(int i =0; i < k; i++){
            System.out.print(Pothole_case[i]);
        }

    }

2017/07/31 23:44

Geon Woo Park

C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        printf("no argc 2 !!!\n");
        return 0;
    }
    char* str = (char*)malloc(sizeof(char)*strlen(argv[1]));
    char* tmp = (char*)malloc(sizeof(char)*strlen(argv[1]));
    str = argv[1];
    int count = 1;
    strcpy(tmp,str);
    printf("%s\n",str);
    for(int i=0;i<strlen(str);i++)
    {
        if((int)str[i]>64 && (int)str[i] <91)
        {
            int tmp2 = (int)str[i]+32;
            str[i] = '_';
            str[i+1] = (char)tmp2;
            for(int j=i+1;j<strlen(tmp);j++)
            {
                str[j+1] = tmp[j];
            }
            str[strlen(tmp)+1] = NULL;
            printf("%s",str);
            break;
        }
    }


    return 0;
}

2017/08/09 11:06

임꺽정

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String content = br.readLine();
        camelToPothole(content);
        br.close();
    }
    public static void camelToPothole(String content) {
        String changedContent = "";
        for (int i=0; i<content.length(); i++) {
            char data = content.charAt(i);
            if (data >= 'A' && data <= 'Z') {
                data += 32;
                changedContent = changedContent.concat("_" + Character.toString(data));
            } else if (data >= '0' && data <= '9') {
                changedContent = changedContent.concat("_" + data);
            } else {
                changedContent = changedContent.concat(Character.toString(data));
            }
        }
        System.out.println("결과 : " + changedContent);
    }
}

2017/08/22 16:09

임주성

import re

def lowerChar(c):
    return '_' + c.group().lower()

def getPotholeCase(str1):
    result = re.sub('[A-Z0-9]',lowerChar,str1 )
    print(str1,'-->', result)

getPotholeCase('codingDojang')
getPotholeCase('numGoat30')

2017/08/24 16:49

piko

public class Example90 {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        String s = "numGoat30";

        for (char ch : s.toCharArray()) {
            if (Character.isUpperCase(ch) || Character.isDigit(ch)) {
                sb.append("_" + Character.toLowerCase(ch));
            } else {
                sb.append(ch);
            }
        }

        System.out.println(sb.toString());
    }
}

2017/08/29 18:31

흑돼지

# python 3.6
def camel2pothole(string):
    rst = "".join(["_" + s.lower() if s == s.upper() or s.isdigit() else s for s in string])
    return rst


print(camel2pothole("codingDojang"))
print(camel2pothole("numGoat30"))

2017/09/08 18:00

mohenjo

JAVA

    public static void main(String[] args) {
        String st = "numGoat30";
        String[] stList = st.split("");
        int len = stList.length;
        String result = "";

        for(int i = 0; i < len; i++) {
            if(i != 0) {
                if(Character.isUpperCase(st.charAt(i)) || Character.isDigit(st.charAt(i)) || Character.isDigit(st.charAt(i - 1))) {
                    stList[i] = "_" + stList[i].toLowerCase();
                }
            }
        }

        len = stList.length;

        for(int i = 0; i < len; i++) {
            result += stList[i];
        }

        System.out.println(result);
    }

2017/09/13 10:09

androot

# 한글 처리 in Atom 1.21.1 + Anaconda(Python 3.6.3)
import sys
import io

sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding='utf-8')

# 파이썬과 같은 몇몇 프로그래밍 언어는 Pothole_case 를 더 선호하는 언어라고 합니다.
# Example:
# codingDojang --> coding_dojang
# numGoat30 --> num_goat_3_0
# 위 보기와 같이 CameleCase를 Pothole_case 로 바꾸는 함수를 만들어요!

text = input("CameleCase로 입력하세요 : ")

if text[0].isupper():
    text[0] = text[0].lower()
print("Pothole_case로 바꾸면 :", ''.join(['_' + c.lower() if c.isupper() or c.isnumeric() else c for c in text]))

2017/11/04 21:00

Jace Alan

def chng_name_cnvntn (str):
    new_str = str[0]     # 첫 번째 문자는 그대로 갑니다
    numb = list('0123456789')

    for i in str[1:]:
        if i.isupper() or i in numb:
            if i == str[-1]:
                new_str = new_str + i.lower()    # 마지막 문자는 끝에 "_" 을 넣지 않습니다
            else:
                new_str = new_str + "_"  + i.lower()
        else:
            new_str = new_str + i

    return new_str

print (chng_name_cnvntn('CodingDojang'))
print (chng_name_cnvntn('numGoat30'))

2017/11/16 18:00

vkospi

char = "CodingDojang"
new=char[0]
for ch in char[1:] :
    if ch.islower() : new = new + ch
    elif ch.isupper() : new = new + "_" + ch.lower() # 함수뒤에는 꼭 () !!!!!!!!!!!!!
    else : new = new+ "_" + ch 
new

python 3.5입니다 첫글자는 뼤고 적용하도록 짜봤습니다.

2017/11/18 00:02

Seohyun Choi

python 문자열에 있는 숫자에 대해서 작업을 할 때 조금 억지로 처리했습니다. 아직 미숙해서..

def change(a):
    b = a.lower()
    A = list(a)
    B = list(b)
    for i in range(len(a)):
        if i == 0: continue
        if a[i] != b[i]: A[i] = '_' + B[i]
        if ord(a[i]) in range(65, 123): 
            if ord(a[i]) in range(91, 97): A[i] = '_' + A[i]
        else: A[i] = '_' + A[i]
    ans = "".join(A)
    print(ans)

a = 'ImSuperMan24'
change(a)

2017/11/19 01:23

이택성

import re

inp = 'numGoat30'
print(re.sub('([A-Z0-9])', '_\g<1>', inp).lower())

2017/11/23 13:38

songci

python입니다

import re

def chang_Pothole_case():
    str_input = input("입력하세요 : ")
    p = re.compile('[0-9A-Z]')
    kk = p.findall(str_input)
    idx = []

    for x in range(len(kk)):
        for y in  range(len(str_input)):
            if kk[x] == str_input[y]:
                idx.append(y)
    s_idx = (sorted(set(idx), reverse=True))

    for r in s_idx:
        if r != 0:
            str_input = "_".join([str_input[:r], str_input[r:]])

    return print(str_input.lower())

chang_Pothole_case()

2017/12/03 02:15

홍철현

def trans(name, count=1):
    tmp=name
    if count>=len(tmp):
        return(tmp[0].lower()+tmp[1:])
    else:
        tmpp=''
        if count<len(tmp)-1:
            tmpp=tmp[count+1:]

        if tmp[count].isupper():
            tmp=tmp[:count]+'_'+tmp[count].lower()+tmpp
            return(trans(tmp, count+2))
        elif tmp[count].isdigit():
            tmp=tmp[:count]+'_'+tmp[count]+tmpp
            return(trans(tmp, count+2))
    return(trans(tmp, count+1))

name=str(input('name: '))
print(trans(name))

2017/12/13 00:01

빗나감

txt = list("codingDDDojang3333")
pot = {x:'_'+x.lower() for x in txt if x==x.upper() or x.isnumeric()}
for k,v in pot.items() : 
    print(k,v)
    for i in range(txt.count(k)):
        txt[txt.index(k)]=v
result = ""
for x in txt :
    result +=x
print(result)

2017/12/17 15:48

얏홍

# 1달 배운 파이썬 병아리 입니다 잘부탁드립니다!
sentence = input("CameleCase를 입력하시오: ")
upper_list = ['A','B','C','D','E','F','G','H','I','J','K','L','N','M','O','P','G','R','S','T'
              ,'U','V','W','X','Y','Z']
number_list = ['1','2','3','4','5','6','7','8','9','0']
store = []
for i in sentence:
    if i in upper_list:
        store.append("_"), store.append(i.lower())
    elif i in number_list:
        store.append("_"), store.append(i)
    else:
        store.append(i)
        continue
finish = ''.join(store)
print(finish)

2017/12/19 17:11

june davis

자바

package cddj;
import java.util.Scanner;

public class cddj10 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter Sentence : ");
        String S = input.nextLine();
        String ans = "";
        char[] Ss = S.toCharArray();
        for (int i = 0; i < Ss.length; i ++) {
            if (Character.isUpperCase(Ss[i])) {
                char part = Character.toLowerCase(Ss[i]);
                ans += "_" + part;
                continue;
            }
            if (Character.isDigit(Ss[i]) ) {
                ans += "_" + Ss[i];
                continue;
            }
            ans += Ss[i];
        }
        System.out.println(ans);
    }

}

2017/12/21 14:24

이택성

파이썬

def isnumber(x):
    try:
        float(x)
        return True
    except ValueError:
        return False

def main(s):
    pothole = ''
    result = ''
    for i in s:
        if i.isupper():
            pothole += '_' + i.lower()
        elif isnumber(i):
            pothole += '_' + i
        else:
            pothole += i
    if pothole[0] == '_':
        pothole = '' + pothole[1:]     

    print("\n","☞ Pothole_case : ", pothole)

s = input(" ▶ 문자열을 입력하세요 : ")

main(s)
  • 결과값
 ▶ 문자열을 입력하세요 : codingDojang

 ☞ Pothole_case :  coding_dojang
▶ 문자열을 입력하세요 : numGoat30

 ☞ Pothole_case :  num_goat_3_0

2017/12/22 11:09

justbegin

        System.out.println("CameleCase : "+a);
        char[] chararr = a.toCharArray();
        String newString = "";
        for(int i=0; i<chararr.length; i++)
        {
            int checkval = (int)chararr[i]-48;
            //숫자일 경우 앞에 _를 붙임
            if(checkval >=0 && checkval <10)
            {
                newString+="_"+String.valueOf(chararr[i]);
            }
            //대문자일 경우 앞에 _ 붙이고 소문자로 
            else if(checkval >16 && checkval <43)
            {
                newString+="_"+String.valueOf(chararr[i]).toLowerCase();
            }
            //둘다 아닐경우 그대로 붙임
            else
            {
                newString+=String.valueOf(chararr[i]);
            }

        }
        System.out.println("Pothole_case : "+newString);

char->int 변경 시 -48을 해줘야 한다는 점만 주의하면 될 것 같습니다. 아니면 (int)'z' 등을 비교하는 식으로 가도 될 것 같네요

2017/12/22 15:42

김준학

Python 3.6

word = input('Enter a CamelCase word: ')
for i in word:
    if i.isupper():
        word = word.replace(i, '_'+i.lower())
    elif i.isnumeric():
        word = word.replace(i,'_'+i)
print('Pothole_case:', word)

2018/01/01 22:10

최상혁

def changePotholeCase(camel_case):
    spelling = list(camel_case) # 입력받은 string을 문자 하나하나씩 쪼갬
    pothole_case = ""

    for s in spelling:
        temp = str(s)
        if temp.isupper():
            temp = "_" + temp.lower() # 대문자를 _소문자로 변경
        elif temp.isdigit(): # isdigit() : 정수로 변환 가능하면 True, 아니면 False
            temp = "_" + temp # 숫자를 _숫자로 변경

        pothole_case += temp # 쪼갠 문자들을 다시 합침

    print(pothole_case)

2018/01/03 00:51

임지호

def pothole_case(s):
    for c in s:
        if c.isupper() or c.isdigit():
            s = s.replace(c, '_' + c.lower())
    return s



if __name__ == '__main__':
    print(pothole_case('codingDojang'))
    print(pothole_case('numGoat30'))

2018/01/13 21:03

Analyticsstory

Python 3.6

def Pothole_case(a):
    print(*["_"+i.lower() if i.isupper() or i.isnumeric() else i for i in a],sep="")
Pothole_case("codingDojang")
Pothole_case("numGoat30")

2018/01/25 17:58

Taesoo Kim

def is_integer(str):
    a = str
    try:
        int(a)
        return True
    except ValueError:
        return False



def change(str):
    a = str
    b = len(a)
    c = list(a)
    result = ''
    for i in range(b):
        if a[i] == a[i].upper() and not(is_integer(a[i])) and a[i] != '_':
            c[i] = '_' + a[i].lower()
    for j in range(b):
        if (is_integer(a[j])) and (a[j] != '_'):
            c[j] = '_' + a[j]
    for i in range(b):
        result += c[i]
    return result

2018/02/04 00:23

김동하

def Camel_to_Snake():
    Camel_str=input("문자열을 입력하세요\n")
    Snake_str = Camel_str[0]
    Camel_str=Camel_str[1:]
    for k in Camel_str:
        if k.isupper():
            Snake_str+="_"+k
        elif k.isdigit():
            Snake_str+="_"+k
        else:
            Snake_str+=k

    return Snake_str

print(Camel_to_Snake())

2018/02/16 05:07

D B

자바입니다!

package CodingDojang;

import java.util.*;

public class CamelCaseConver {

    private static String converter(String input) {
        String[] output;
        String convertedString = "";

        output = input.split("");
        for(int i = 0; i < output.length; i++) {
            if(output[i].matches("[A-Z|0-9]")) {
                output[i] = output[i].toLowerCase();
                convertedString += ("_" + output[i]);
            } else {
                convertedString += output[i];
            }
        }
        return convertedString; 
    }

    public static void main(String args[]) {
        Scanner scn = new Scanner(System.in);
        String input = scn.nextLine();

        System.out.println(CamelCaseConver.converter(input));
        scn.close();
    }
}

2018/02/22 23:14

sangw0804

public class PatholeCase {
    public static void main(String[] args) {
        String str1 = "codingDojang30";
        char[] strArr = str1.toCharArray();

        for (int i = 0; i < strArr.length; i++) {
            if(Character.isUpperCase(strArr[i])) {
                System.out.print("_"+ String.valueOf(strArr[i]).toLowerCase());
            }
            else if(Character.isDigit(strArr[i])){
                System.out.print("_"+ strArr[i]);
            }
            else
                System.out.print(strArr[i]);
        }
    }
}

2018/03/06 17:16

강성민

def main():
    camele = input()
    pothole = []

    for i in range(0, len(camele)):

        if 'A' <= camele[i] and camele[i] <= 'Z':
            pothole.append("_")
        elif '0' <= camele[i] and camele[i] <= '9':
            pothole.append("_")

        pothole.append(camele[i])

    print("".join(pothole))

2018/03/07 23:13

이승훈

def changecase(camelCase):
    result = ''
    for astr in camelCase:
        args = 32
        while chr(args) != astr:
            args = args + 1
        if args in range(48, 58) or args in range(65, 91):
            if camelCase.find(astr) != 0:
                result = result + '_'
        if not result:
            result = result + astr
        elif result[-1] == '_' and args in range (65, 91):
            result = result + chr(args + 32)
        else: result = result + astr
    return result

Python 3입니다. 위에보니까 훨씬 직관적으로 하신분들 많네요...

2018/03/10 23:10

myyh2357

def trans_string(str):
    res = ""
    for i in str:
        if i.isupper() == True and i==1:
            return res
        if i.isupper() == True:
            res +=  "_"+ i.lower()
        elif i.isdigit() == True:
            res +=  "_" + i
        else:
            res += i
    return res


finalStr = trans_string("numGoat30")
print(finalStr)


2018/03/21 17:08

bnewkk

멋지지는 않지만 남겨 봅니다.^^;

import re

def camel_to_snake(input):
    p = re.compile('[A-Z0-9]')
    i_list = []
    for a in p.finditer(input):
        i_list.append(a.span()[0])

    i = 0
    sn_text = ''
    for t in input:
        if i_list.count(i) > 0:
            sn_text = sn_text + '_' + t.lower()
        else:
            sn_text = sn_text + t
        i = i + 1

    return sn_text


print(camel_to_snake("numGoat30"))

2018/03/27 15:29

무명소졸

Swift입니다. String의 reduce를 이용해서 변환을 했습니다.

import Foundation

var lookupData = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

func translate(_ msg: String) -> String {
    return msg.reduce("", { return $0 + (lookupData.contains($1) ? "_" + String($1) : String($1)) }).lowercased()
}

print(translate("codingDojang30"))
print(translate("thisIsSwift40"))

결과는...

coding_dojang_3_0
this_is_swift_4_0

2018/03/28 02:58

졸린하마

    public static void camelToPothole() throws NumberFormatException, IOException {
        String oStr = "";
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Camel Case 로 입력하시오. : ");
        String iStr = br.readLine();
        br.close();
        char[] charArr = iStr.toCharArray();
        for(int i = 0; i < charArr.length; i++) {
            if(charArr[i] >= 'A' && charArr[i] <= 'Z') {
                oStr = oStr + "_";
                charArr[i] += 32;
            } else if(charArr[i] >= '0' && charArr[i] <= '9') {
                oStr = oStr + "_";
            }
            oStr = oStr + charArr[i];
        }
        System.out.print(iStr + " 의 Pothole Case 는 : " + oStr + "\n");
    }

2018/03/28 16:56

이준석

python3 입니다

def Pothole_case(cameleCase):
    Pothole_case = ''
    for alphabet in cameleCase:
        if alphabet.islower():
            Pothole_case += alphabet
        elif alphabet.isupper():
            Pothole_case += '_' + alphabet.lower()
        else:
            Pothole_case += '_' + alphabet
    print(Pothole_case)
    return Pothole_case

cameleCase = input('변수를 입력하세요: ')
Pothole_case(cameleCase)

2018/04/01 21:48

totorodot

public static void main(String[] args) throws Exception {

        String str = "numGoat30"; //num_goat_3_0
        StringBuffer sb = new StringBuffer(str);
        int cnt = 0;
        for (int i=0, j=1; i<str.length()-1; i++, j++) {
            if (('a' <= str.charAt(i) && str.charAt(i) <= 'z') && ('A' <= str.charAt(j) && str.charAt(j) <= 'Z')) {
                String lower = (str.charAt(j)+"").toLowerCase();
                char ch = lower.toCharArray()[0];
                sb.setCharAt(j, ch);
                sb.insert(j, "_");
                cnt++; // 문자열이 길어진 만큼 카운트
            }
            if (('a' <= str.charAt(i) && str.charAt(i) <= 'z') && ('0' <= str.charAt(j) && str.charAt(j) <= '9')) {
                sb.insert(j+cnt, "_");
                cnt++;
            }
            if (('0' <= str.charAt(i) && str.charAt(i) <= '9') && ('0' <= str.charAt(j) && str.charAt(j) <= '9')) {
                sb.insert(j+cnt, "_");
                cnt++; 
            }
        }
        System.out.println(sb);
    } // 자바입니다. 엄청 더럽게 풀었네요

2018/05/06 16:39

정몽준

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ConvertCamelToPothole {
    public static void main(String[] args) {


        String input = "codingDojang";

        System.out.println("before  : " + input);

        String result = convert(input);

        System.out.println("After   : " +  result);
    }

    public static String convert(String input) {


        int inputSize = input.length();

        for (int i = 0 ; i < inputSize ; i++) {
            if (Character.isUpperCase(input.charAt(i))) {
                String str = String.valueOf(input.charAt(i));
                input = input.replace(str, "_" + str.toLowerCase()); 
            }
        }


        Pattern p = Pattern.compile("\\d");
        Matcher m = p.matcher(input);

        while (m.find()) 
            input = input.replace(m.group(0), "_" + m.group(0));

        return input;
    }
}

2018/05/21 10:47

聂金鹏

# for문을 활용한 방법
def camel2pothole1(str1):
    str2 = ""
    for char in str1:
        if char.isdigit() or char.isupper():
            str2 += "_"
        str2 += char
    return str2.lower()

# 정규표현식을 활용한 방법
import re
def camel2pothole2(str1):
    pat = re.compile("([A-Z0-9])")
    return pat.sub('_\g<1>', str1).lower()

str1 = "codingDojang"
str2 = "numGoat30"

print(camel2pothole1(str1))
print(camel2pothole1(str2))
print(camel2pothole2(str1))
print(camel2pothole2(str2))

2018/05/23 22:56

재즐보프

Python 3.6

def pothole_case(letter):
    newletter = []
    for l in str(letter):

        if l.isupper():
            l = "_" + l.lower()
            newletter.append(l)
        elif l.isdigit():
            l = "_" + l
            newletter.append(l)
        else:
            newletter.append(l)

    print("".join(newletter))
    return newletter

2018/05/24 11:09

Gerrad kim

text = input("CameleCase입력")
result=[]
for i in text:
    if i.isupper():
        result.append("_"+i.lower())
    elif i.isdigit():
        result.append("_"+i)
    else:
        result.append(i)

print("".join(result))

2018/05/29 05:24

조성은

Python

test = ["codingDojang", "numGoat30"] #test = input().strip().split(' ')
answer = []
for t in test:
    output = ""
    for s in t:
        if s.isupper():
            output += "_" + s.lower()
        elif s.isdigit():
            output += "_" + s
        else:
            output += s
    answer.append(output)
print(*answer)

2018/05/30 16:44

Taesoo Kim

input_string = input("입력할 문자열은?")
new_str = ''

for i in input_string:
    if i.isupper() == True or i.isdecimal() == True:
        new_str = new_str + "_" + i
    else:
        new_str += i

print(new_str.lower())

2018/06/03 22:03

meteor

def getpothole(CameleCase):
    PotholeCase = ""
    length = len(CameleCase)
    upperexist = False

    for index, letter in enumerate(CameleCase):
        if letter.isupper():    # 대문자를 발견한다면
            PotholeCase = CameleCase[:index] + '_' + CameleCase[index].lower()  # 대문자 전까지 슬라이싱 +  '_' + 대문자를 소문자로 변환

            if index != length-1:   # 뒤에 문자열이 더 남았다면
                PotholeCase += getpothole(CameleCase[index+1:])     # 이후의 문자열에 대한 재귀호출
            upperexist = True
            break

        elif letter.isnumeric():    # 숫자를 발견한다면
            PotholeCase = CameleCase[:index] + '_' + CameleCase[index] # 숫자 전까지 슬라이싱해서 저장

            if index != length - 1: # 뒤에 문자열이 더 남았다면
                PotholeCase += getpothole(CameleCase[index + 1:])  # 이후의 문자열에 대한 재귀호출
            upperexist = True
            break

    if not upperexist:
        PotholeCase += CameleCase

    return PotholeCase


CameleCase1 = "codingDojang"
CameleCase2 = "numGoat30"

PotholeCase1 = getpothole(CameleCase1)
PotholeCase2 = getpothole(CameleCase2)

print(PotholeCase1)
print(PotholeCase2)

2018/06/11 19:42

Hand

camele = 'python36CodingDojang'
pothole = ''
for i in camele:
    if i.isupper() or i.isdigit(): pothole+='_'+i.lower()
    else: pothole+=i
print(pothole)

2018/06/24 08:34

Creator

import re

conv = lambda x:re.sub('[A-Z0-9]', lambda m:"_"+m.group().lower(),x)    
print(conv("testEserThink093"))

2018/07/04 15:57

nabina

파이썬입니다.

s = input("Enter the string: ")
for c in s:
    if c.isupper() or c.isdecimal() : s = s.replace(c, "_" + c)
print("Pothole_case: " + s.lower())

2018/07/24 20:38

김준영

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main()
{
    char ch[50];
    scanf("%s",ch);
    char *ptr;

    ptr = ch;
    for(int i=0; i< strlen(ch); i++)
    {
        if(ch[i] == toupper(ptr[i]))
            {
            for(int j = strlen(ch)+1; j >= i; j--)
                {
                    ptr[j+1]= ptr[j];
                } 
            ptr[i] = '_';
            ptr[i+1]=tolower(ptr[i+1]);
            break;
            }
   } 
    printf("%s",ptr);
}

2018/07/27 13:59

Jaeju An

const verifyCamelCase = name => {
  let verifiedName = ''

  for (let char of name) {
    isRegSuccess =  /[0-9A-Z]/.test(char) 

    isRegSuccess
      ? verifiedName += '_' + char
      : verifiedName += char
  }

  return verifiedName
}

2018/08/04 11:24

김병관

import re
t=re.compile('[A-Z]|[0-9]')
def Pothole(text):
    result=[]
    for i in range(len(text)):
        if t.findall(text[i]):
            result+='_',text[i].lower()
        else:
            result+=text[i]
    print(''.join(result))

Pothole('codingDojang')
Pothole('numGoat30')

2018/08/11 14:00

S.H

def PC(s):
    r = str()
    for i in s:
        if i.isupper(): i = '_' + i.lower()
        elif i.isdigit(): i = '_' + i.lower()
        r += i
    return r

2018/08/22 16:24

김건우

루비입니다

def toPothole str
    str.gsub(/[A-Z0-9]/, '_\0').downcase()
end

2018/08/23 16:34

아뇩다라삼먁삼보리

파이썬 3

def pothole(a) :

    result = ''

    for idx, chr in enumerate(a) :

        if chr.isupper() :

            result += '_'+a[idx].lower()

        elif chr.isdigit() :

            result += '_'+a[idx]

        else :

            result += a[idx]

    return result

a = 'numGoat30'

print(pothole(a))

2018/09/08 22:48

박강민

//  ============================================
        String temp = "numGoat30";
        String temp1 = "";

        for (int i = 0; i < temp.length(); i++) {
            if (temp.substring(i, i + 1).matches("[A-Z0-9]")) {
                temp1 += "_" + temp.substring(i, i + 1).toLowerCase();
            } else {
                temp1 += temp.substring(i, i + 1);
            }
        }
        System.out.println(temp1);

2018/09/11 18:09

채규빈

a=input()
b=''

for x in a:
    if x==x.upper():
        b+='_%s'%(x.lower())
    elif type(x)==int:
        b+='_%s'%x
    else:
        b+=x

print(b)

2018/09/11 19:44

전형진

import re

def camel_to_pothole2(str1):
    p = re.compile("([A-Z0-9])")
    m = p.sub("_\g<1>", str1)
    return m.lower()

정규 표현식을 활용한 풀이 방법입니다. 아직 많이 부족하네요...

2018/09/11 20:43

문승현

s = input()

l = []
for c in s:
    if c.islower():
        l.append(c)
    elif c.isupper():
        l.append("_" + c.lower())
    elif c.isdigit():
        l.append("_" + c)

print("".join(l))

2018/09/19 05:13

Charlie Jeong

a="Aas4dfB3"
count=0;
for i in a:    
    #숫자일 경우    
    if count!=0 and ord(i)>=48 and ord(i)<=57 :       
        a=a[:count]+"_"+a[count:]
        count+=1
    # 대문자일 경우    
    if count!=0 and ord(i)>=65 and ord(i)<=90 :
        a=a[:count]+"_"+a[count:]
        count+=1
    count+=1
a=a.lower()
print(a)

2018/09/25 12:17

쨔이

word = 'ParkJongHyuk95'
result = ''
for x in word:
    if x.isupper() or x.isdigit():
        result += '_'
    result += x.lower()
print(result[1:])

2018/10/01 14:23

Hyuk

def cameltopothole(str):
    tmp_str=''
    for i in str:
        if i.isupper() or i.isdigit():
            tmp_str = tmp_str + '_'+i
        else:
            tmp_str = tmp_str + i

    return tmp_str.lower()

print(cameltopothole('numGoat30'))

2018/10/25 13:44

Dae Su Jeong

strexample = input('문자열을 입력하세요. : ')
strre= ''

for x in strexample :
        if x==x.upper() :
                strre += '_' + x.lower()
        else :
                strre+=x


print(strre)

2018/10/28 22:59

빅디펜스

def Pothole(camel):
    pothole = ""
    for char in camel:
        if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789":
            pothole += "_" + char.lower()
        else:
            pothole += char
    print(pothole)

Pothole(input("카멜케이스 입력 : "))

2018/10/29 13:08

그사람 남한 볼 수 있어요

#define _CRT_SECURE_NO_WARNINGS

#include <windows.h>
#include <stdio.h>

#define STR_LEN 256


int main(void) {
    char str[STR_LEN];
    //codingDojang ,, numGoat30 input
    printf("Input : ");
    scanf("%s",str);
    char rst[STR_LEN];
    int len = 0 ;
    for (int i = 0; i < strlen(str); i++) {
        if (isupper(str[i])) {
            rst[len++] = '_';
            rst[len] = tolower(str[i]);
        }
        else if (isdigit(str[i])) {
            rst[len++] = '_';
            rst[len] = str[i];
        }
        else {
            rst[len] = str[i];
        }
        len++;
    }
    rst[len] = '\0';
    printf("%s -> %s", str, rst);
    system("pause");
    return 0;
}

2018/11/24 23:51

김범준

# python 3.7.1

def to_pathole(string):
    for char in string:
        if char.isupper() or char.isdigit():
            string = string.replace(char, '_' + char.lower())

    return string

print(to_pathole('codingDojang'))
print(to_pathole('numGoat30'))

2018/12/03 11:44

정지환

def pothole(string):

     return ''.join('_' + x.lower() if x.isupper() or x.isdecimal() else x for x in string)

2018/12/06 23:48

권순명

def convert_camel_to_pothole(a_string):
    converted = ""
    for i, ch in enumerate(a_string):
        if str(ch).isupper():
            converted = converted + "_" + str(ch).lower()
        else:
            converted = converted + str(ch)
    return converted

if __name__ == '__main__':
    print convert_camel_to_pothole('potHole')

2018/12/21 09:41

RumbleBang

CamelCase = list(input())
for number, i in enumerate(CamelCase):
    if not i.islower():
        i = i.lower()
        CamelCase.insert(number, '_')

print(''.join(CamelCase))

2019/01/03 20:28

Woohyuck Choi

string = input()
def ca_to_po (string):
    bag = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    return ''.join(['_' + c.lower() if c in bag else c for c in string])
print(ca_to_po(string))

2019/01/14 15:43

D.H.

def pothole(camel):
    camel = list(camel)
    for x in range(len(camel)):
        if camel[x].isupper() or camel[x].isdigit():
            camel.insert(x,'_%s' %(camel[x] if camel[x].isdigit() else camel[x].lower()))
            del camel[x+1]
    return ''.join(camel)

2019/01/20 14:05

김영성

def Pothole_case(s):
    emp=''
    for i in s:
        if i.isupper():
            i='_'+i.lower()
        elif i.isdigit():
            i='_'+i
        emp+=i
    return emp

print(Pothole_case('codingDojang'))


2019/01/21 21:49

jj kim

javascript풀이 입니다.

1. 문제

파이썬과 같은 몇몇 프로그래밍 언어는 Pothole_case 를 더 선호하는 언어라고 합니다.

Example:

codingDojang --> coding_dojang

numGoat30 --> num_goat_3_0

위 보기와 같이 CameleCase를 Pothole_case 로 바꾸는 함수를 만들어요!

2.풀이

function trans(str){
  const splitted = str.split('')
  const memory = []
  for(let i=0; i<splitted.length; i++){
    if(splitted[i] === splitted[i].toLowerCase()&&isNaN(Number(splitted[i]))===true){
      memory.push(splitted[i])
    }else{
      memory.push('_'+splitted[i].toLowerCase())
    }
  }
  return memory.join('')
}
trans('codingDojang')
//출력값: 'coding_dojang'
trans('numGoat30')
//출력값: 'num_goat_3_0'

2019/01/22 18:22

돌도끼

def changer(a):
    result = ''
    number = '1, 2, 3, 4, 5, 6, 7, 8, 9, 0'
    for alphabet in a:
        b = alphabet.lower()
        if alphabet != b or alphabet in number:     #글자가 소문자와 다르거나
            alphabet = '_' + b                      #숫자일 경우,
            result += alphabet                      #글자에 _를 더하고
        else:                                       #결과값에 저장
            result += alphabet                      #나머지는 그대로 저장
    return print(result)


changer('codingDojang')
changer('numGoat30')

2019/01/29 18:11

손태호

var input = 'codingDojang';

var result = input.replace(/[A-Z0-9]/g, function (a, b, c) {
    return '_' + a.toLowerCase();
});

console.log(result);

2019/02/20 14:45

이계민

import re
data = 'numGoat30'
p = re.compile('([A-Z])')
m = p.sub('_\g<1>',data).lower()
p = re.compile('([0-9])')
n = p.sub('_\g<1>',m)
print(n)

2019/02/25 15:52

def camel_to_pothole (camel):
    _result = []
    chars = list(camel)
    for char in chars:
        if char.isupper():
            char = '_' + char.lower()
        _result.append(char)
    return ''.join(_result)

camel = str(input("CameleCase 입력: "))
print(camel_to_pothole(camel))

2019/02/26 16:07

Nonamed

namespace codingdojang__
{
    class Program
    {
        static void Main(string[] args)
        {
            Case("codingDojang");
            Case("numGoat30");
        }
        static void Case(string input)
        {
            string temp = input.ToLower();
            int e = 0;
            for (int i = 1; i < input.Length; i++)
            {
                if(input[i] != temp[i] || int.TryParse(input[i].ToString(), out e) == true)
                {
                    temp = temp.Insert(i, "_");
                    input = input.Insert(i, " ");
                    i++;
                }
            }
            Console.WriteLine(temp);
        }
    }
}

2019/03/07 18:32

bat

def pothole_case(string):
    anw = ''
    for i in string:
        if i.isupper() or i.isnumeric():
            anw += ('_'+str(i.lower()))
        else: 
            anw += i
    return anw

2019/03/10 23:02

dodoman

import re

def camel_to_pothole(s):
    return re.sub('[A-Z0-9]', lambda m : '_' + m.group(0).lower(), s)

2019/05/01 15:35

messi

a=input("CameleCase입력: ")
number=['0','1','2','3','4','5','6','7','8','9']
Big=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
result=""
for i in a:
    if i in Big:
        result=result+'_'+chr(ord(i)+32)
    elif i in number:
        result=result+'_'+i
    else:
        result=result+i
print(result)

2019/08/28 00:31

박재욱

PHP

$fn = function(string $str) : string {
    return strtolower(preg_replace("/([A-Z0-9])/", "_$1", $str));
};

print_r($fn('codingDojang')); // coding_dojang
print_r($fn('numGoat30')); // num_goat_3_0

2019/09/11 16:03

d124412

python 3.5.2 풀이 참조

def change(str):
    largenumber = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    return ''.join(['_'+x.lower() if x in largenumber else x for x in str])

print(change('numGoat30'))

2019/09/19 10:45

Dreaming Pug

def replace_case(target):
    result = ""
    for i in range(len(target)):
        if(target[i].isupper()):
            result = result + "_" + target[i].lower()
        elif(i > 0 and target[i].isdigit() and target[i-1] is not '_'):
            result = result + "_" + target[i]
        else: result = result + target[i]
    return result

2019/09/23 14:48

Sangwoon Park

public class Camelase를Pothole_case로바꾸기 {

    public static void main(String[] args) {
        Pothole_case("codingDojang");
        Pothole_case("numGoat30");
    }

    public static void Pothole_case(String str) {

        StringBuffer line = new StringBuffer();
        for(int i=0; i<str.length(); i++) {
            char ch = str.charAt(i);
            if(Character.isUpperCase(ch)==true) {
                line.append("_");
                line.append(Character.toLowerCase(ch));
            }
            else if(ch>47&&ch<58) {
                line.append("_");
                line.append(ch);
            }
            else {
                line.append(ch);
            }
        }
        System.out.println(line);
    }
}

2019/11/25 17:12

big Ko

파이썬3입니다. 첫 문자는 제외하고 규칙이 적용되도록 짜봤습니다.

def Pothole_case(a):
  b = a[1:]
  result = ''
  for x in str(b):
    if x == x.upper(): result += '_' + x.lower()
    elif x.isdigit(): result += '_' + x
    else: result += x
  return a[0] + result

print(Pothole_case('codingDojang'))    # coding_dojang
print(Pothole_case('CodingDojang'))    # coding_dojang
print(Pothole_case('numGoat30'))    # num_goat_3_0
print(Pothole_case('123numGoat30'))    # 1_2_3num_goat_3_0

2019/12/28 18:13

Sean


data = "codingDojang35"
result =""
Run = True
i = 0
lenth = len(data)
while Run :    
    if i < lenth:
        if  65 <= ord(data[i]) <= 90:
            data = data.replace(data[i],"_"+data[i].lower())
            i+=2
            lenth += 1
        elif 48 <= ord(data[i]) <= 57:
            data = data.replace(data[i],"_"+data[i])
            i+=2
            lenth += 1    
        else :
            i +=1
    else :
        Run = False

print(data)


2020/01/19 00:04

semipooh

python 3.8

import re
a="codingDozang30"
print(re.sub("([\w])","_\g<0>",a).lower())

2020/03/03 05:33

mr. gimp

#include<iostream>
#include<string>
using namespace std;
/*
파이썬과 같은 몇몇 프로그래밍 언어는 Pothole_case 를 더 선호하는 언어라고 합니다.

Example:
codingDojang --> coding_dojang
numGoat30 --> num_goat_3_0

위 보기와 같이 CameleCase를 Pothole_case 로 바꾸는 함수를 만들어요!
*/

void Func(string s) {
    cout << s << " -> ";
    for (int i = 0; i < s.length(); i++) {
        if ((int)s[i] >= 65 && (int)s[i] <= 90) {
            cout << '_' <<(char)(s[i] + 32);
            continue;
        }
        if ((int)s[i] >= 48 && (int)s[i] <= 57) {
            cout << '_' << s[i];
            continue;
        }
        cout << s[i];
    }
    cout << endl;
}

int main() {
    Func("codingDojang");
    Func("numGoat30");
}

2020/03/25 15:06

++C

def Pothole_case(a):
    for i in range (len(a)):
        if ord(a[i])>=65 and ord(a[i])<=90:
            print('_'+chr(ord(a[i])+32),end='')
        elif ord(a[i])>=48 and ord(a[i])<=57:
            print('_'+str(a[i]),end='')
        else:
            print (a[i],end='')

Pothole_case(str(input('text....')))

2020/04/14 13:27

Buckshot

<결과> text....numGoat30 num_goat_3_0 text....codingDojang coding_dojang - Buckshot, 2020/04/14 13:28
def c_poth(string):
    for s in string:
        if s.isupper() or s.isdigit():
             string = string.replace(s, '_' + s.lower(), 1)
    return string

def main():
    print(c_poth('numGoat30'))

if __name__ == '__main__':
    main()

2020/05/03 11:40

Hwaseong Nam


def convert(n) :
    res =""
    for x in n:
        if x.isupper() or x. isdigit():
            x = "_" + x.lower()
        res += x 
    return res

2020/05/03 22:18

최민기

camelcase = str(input())
i = 0
while i < (len(camelcase)):
    if camelcase[i].isupper():
        camelcase = camelcase.replace(camelcase[i], '_'+camelcase[i].lower())
        i += 2
    elif camelcase[i] == '3':
        camelcase[i].isdigit()
        camelcase = camelcase.replace(camelcase[i], '_'+camelcase[i])
        i += 2
    else:
        i += 1
print(camelcase)

2020/05/14 09:28

Money_Coding

word = input("Enter a string: ")
word = [x for x in word]

for i in range(len(word)):
    if word[i].isupper():
        word[i] = "_"+word[i].lower()
    elif word[i].isnumeric():
        word[i] = "_"+str(word[i])[0]

a=""
for j in range(len(word)):
    a = a+word[j]

print(a)

2020/07/29 00:48

김병관

N = list(input())
finallist = []
check = ""
for i in range(len(N)):
    if N[i] == N[i].upper():
        finallist.append(check+"_")
        check = N[i].lower()
    else:
        check += N[i]
final = ""
for j in finallist:
    final += j
print(final+check)

2020/08/15 20:20

BlakeLee

public static void main(String[] args) throws ParseException {

        Scanner scan = new Scanner(System.in);
        System.out.print("입력 : ");
        String lang = scan.next();
        String ediLang = null;
        for(char word : lang.toCharArray()) {
            if(Character.isUpperCase(word)||Character.isDigit(word)) {
                ediLang = lang.replace(String.valueOf(word), "_"+String.valueOf(word).toLowerCase());   
            }
            if(ediLang != null) lang = ediLang;
        }

        System.out.println(ediLang);

2020/10/09 18:59

B A

def camel2pothole(s):
    for i in s:
        if i in upper:
            s = s.replace(i, "_" + i.lower())
        elif i in str(num):
            s = s.replace(i, "_" + i)
    print(s)

2020/11/26 17:21

김우석

def Pothole_case(text):

  answer=[]

  for letter in text:

    if letter==letter.upper():

      answer.append("_")

      answer.append(letter.lower())

    else:

      answer.append(letter)

  print("".join(answer))

Pothole_case("codingDojang")

Pothole_case("numGoat30")

2021/01/02 16:01

전준혁

def Camel_to_Pothole():
    string = input("Input : ")
    string_list = []

    pos = 0
    for i in range(len(string)):
        if string[i].isupper() or string[i].isdecimal():
            string_list.append(string[pos:i])
            pos = i
    string_list.append(string[pos:])

    string_list = list(map(lambda x: x.lower(), string_list))
    return '_'.join(string_list)

2021/02/03 12:09

Ha

def pothole(str1):
    str2=''
    for char in str1:
        if char.isdigit() or char.isupper():
            str2+="_"
        str2+=char
    return str2.lower()

print(pothole("numGoat30"))

2021/02/03 22:04

fox.j

catxt = 'codingDjango3'
potxt = ''

for i in catxt:
    if i.isupper() or i.isdigit():
        potxt += '_' + i.lower()
    else:
        potxt += i

print(potxt)

2021/02/11 18:28

pathworker

def pothole_case(text):
    result = []
    for i in range(len(text)):
        if text[i].isupper() and text[i-1].islower():
            result.append('_'+text[i].lower())
        elif text[i].isdigit():
            result.append('_'+text[i])
        else:
            result.append(text[i])

    return print(''.join(result))

pothole_case('codingDojang')
pothole_case('numGoat30')

2021/02/23 08:30

DSHIN

public class Camel2pothole2 {
    public static void main(String[] args) {
        //Scanner sc = new Scanner(System.in);
        //String input = sc.nextLine();
        String input = "numGoat30";
        System.out.println(camel2pothole(input));
    }
    public static String camel2pothole(String camel) {
        String result = "";
        for (int i = 0; i < camel.length(); i++) {
            if (Character.isUpperCase(camel.charAt(i))) {
                result += "_" + Character.toLowerCase(camel.charAt(i));
            } else if (Character.isDigit(camel.charAt(i))) {
                result += "_" + camel.charAt(i);
            } else {
                result += camel.charAt(i);
            }
        }
        return result;
    }
}

2021/05/28 10:16

박준영

def lowup(w) :
    low =''
    for i in w:
        if 96<ord(i)<123 : low+=i
        else :
            try : low += '_'+i.lower()
            except : low += i
    return low

2021/05/31 16:09

약사의혼자말

def location(n):
    location  = []
    for i in n:
        if i.isupper() == True or i.isdigit() == True:
            location.append(i)
        else: pass
    return location
#
def separate(n):
    n2 = [i for i in n.lower()]
    id = []
    t = 0
    for i in location(n):
        id.append(n.index(i))
    for loc in id:
        n2.insert(loc+t,'_')
        t += 1
    return print(''.join(n2))


separate('numGoat30')

2021/07/19 16:23

ss2663

#codingdojing_camel2_pot

def cam2pot(word):

    res = ''
    for c in word:
        if c.isupper(): res += '_' + c.lower()
        elif c.isdigit(): res += '_' + c
        else: res += c

    print(res)

cam2pot('codingDojang')
cam2pot('numGoat30')


2021/08/12 17:52

Jaeman Lee

def change(a):
    b = '0123456789'
    n = a[0]     
    for i in a[1:]:
        if i.isupper():
            i = '_'+i.lower()
        elif i in b:
            i = '_'+i
        n += i
    return n

if __name__ == '__main__':
    a = input()
    print(change(a))

첫 번째 대문자는 패스했습니다.

2021/10/20 19:51

서현준


a = input("camelCase를 입력해주세요")

def Convert (a):
    arr =[]
    for k in range(len(a)):
        if a[k].isupper():
            arr.append("_")
            arr.append(a[k].lower())
        elif ord(a[k]) >47 and ord(a[k]) <58 :
            arr.append("_")
            arr.append(a[k])
        else:
            arr.append(a[k])
    return print("".join(arr))

Convert(a)

2021/12/31 03:39

양캠부부

user = input('Input camel name : ')
val = range(len(user))
key = [x for x in user]
d = dict(zip(key, val))
for i in key : 
    if i.isupper() == True or i.isnumeric() == True :
        key[d.get(i)] = f'_{i}'
result = ''.join(key)
print(result.lower())

2022/01/02 16:54

bryn0726

_input = input()

for i in _input :
    if ord(i) >= 65 and ord(i) <= 90 : print("_"+i.lower(),end='')
    elif ord(i) >= 48 and ord(i) <= 57 : print("_"+i, end='')
    else : print(i,end='')
print("")


2022/02/03 15:53

강태호

a = 'numGoat30'
for i in a:
    if i.isupper() or i.isdigit():
        print('_'+i.lower(), end='')
    else:
        print(i, end='')

2022/02/14 17:14

로만가

깔끔하게 쓴 것 같습니다 ㅎ

title=input('CameleCase : ')
key1='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

for s in title:
    if s in list(key1):
        title=title.replace(s,"_"+s)
print(title.lower())

2022/03/08 20:53

코딩초보박영규

#두뇌의 한계 ..
example = 'numGoat30'

Alist = {'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15, 'Q': 16, 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24, 'Z': 25}
Aresult = ['_a', '_b', '_c', '_d', '_e', '_f', '_g', '_h', '_i', '_j', '_k', '_l', '_m', '_n', '_o', '_p', '_q', '_r', '_s', '_t', '_u', '_v', '_w', '_x', '_y', '_z']
Nresult = ['_0', '_1', '_2', '_3', '_4', '_5', '_6', '_7', '_8', '_9']

for i in example:
    if i in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
        print(Aresult[Alist[i]],end='')
    elif i in '0123456789':
        print(Nresult[int(i)],end='')
    else:
        print(i,end='')

2022/06/22 18:42

김시영

string = str(input("camelCase를 입력하세요"))
print("".join([i if i.islower() or j == 0 else "_"+i.lower() for j,i in enumerate(string)]))

깔끔하게 한줄코딩! 첫글자가 대문자일때도, 숫자일때도 모두 커버합니다.

2023/08/13 00:16

JGCO

def make_pothole_case(w):
    ans = ''
    for c in w:
        if c.isupper():
            c = c.lower()
            ans += '_'
        elif c.isdigit():
            ans += '_'
        ans += c
    return ans

print('codingDojang --> ', make_pothole_case('codingDojang'))
print('numGoat30 --> ' ,make_pothole_case('numGoat30'))

2023/11/23 20:13

insperChoi

def camel_to_pothole(camel):
    pothole = ''

    for i in range(len(camel)):
        if camel[i].isupper():
            pothole += '_' + camel[i].lower()
        elif camel[i].isdigit():
            pothole += '_' + camel[i]
        else:
            pothole += camel[i]

    return pothole

2023/12/07 17:48

윤영식

목록으로