파이썬과 같은 몇몇 프로그래밍 언어는 Pothole_case 를 더 선호하는 언어라고 합니다.
Example:
codingDojang --> coding_dojang
numGoat30 --> num_goat_3_0
위 보기와 같이 CameleCase를 Pothole_case 로 바꾸는 함수를 만들어요!
출처: UT past test
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
첫번째 문자가 대문자인 경우는 생각하지 않고 대문자나 숫자인 경우 무조건 "_"+소문자로 변경하도록 했습니다.
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')
파이썬입니다.
def do(l):
a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
return "".join(["_" + c.lower() if c in a else c for c in l])
print(do('numGoat30'))
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
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
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);
}
자바로 풀어봤습니다.
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;
}
}
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;
}
$str = "numGoat30";
$keywords = preg_replace_callback("/[A-Z0-9]/",'change',$str);
function change($matches) {
return "_".strtolower($matches[0]);
}
echo $keywords;
파이썬 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'))
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
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)))
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);
파이썬입니다.
import re
print re.sub([A-Z0-9])", "_\\\\1", 'codingDoJang')
print re.sub([A-Z0-9])", "_\\\\1", 'numGoat30')
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
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);
}
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')
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 입니다.
C#에 정규식 사용했습니다.
private string replace(string test)
{
return Regex.Replace(test, @"[A-Z0-9]", delegate(Match match)
{
return "_" + char.ToLower(match.ToString()[0]);
});
}
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();
}
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]));
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"))
파이썬입니다.
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"))
파이썬 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
파이썬이 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))
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
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)
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)
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"
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
}
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
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
파이썬입니다. 가급적 정규식을 안 쓰려고 했는데, 앞의 분이 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'))
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');
}
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))
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"))
>>> import re
>>> pc = lambda src: re.sub(r"([A-Z0-9])", r"_\1", src).lower()
>>> pc('numGoat30')
'num_goat_3_0'
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"))
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;
}
자바입니다. 뭔가 노가다한것같은 기분이 ...... ㅠ
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;
}
}
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)
숫자인 경우는 적용하지 못했습니다.
자바 로 코딩
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());
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);
}
}
strEx = input('문자열을 입력하세요. : ')
strFinal = ''
for one in strEx :
if one.upper() == one :
strFinal = strFinal + '_' + one.lower()
else :
strFinal = strFinal + one
print(strFinal)
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'))
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")
#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;
}
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"))
파이썬
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'))
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
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)
파이썬 초보입니다. 많은 피드백 부탁드립니다!
안녕하세요. 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;
}
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);
}
import re
def to_pothole_case(arg):
return re.sub(r'((?<!^)(?<!_))([A-Z0-9])', r'_\2', arg).lower()
Python 3.5.2에서 작성하였습니다.
자바로 작성했습니다.
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;
}
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'))
아직 눕눕이라...
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)
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 ####
//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;
}
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))
Python
def camelToPothole(inputString):
Pothole =''
for letter in inputString:
if letter.islower():
Pothole =Pothole + letter
else:
Pothole =Pothole + "_" +letter.lower()
return Pothole
/*
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;
}
str1 = "codingDojang"
str2 = "numGoat30"
pothole = ""
for char in str1:
if char.islower():
pothole += char
else:
char = char.lower()
pothole = pothole + "_" + char
print(pothole)
#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;
}
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
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);
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());
}
}
camel = "codingDojang"
def Pothole(cam):
x = sorted(cam)[0]
return cam.replace(x, "_" + x.lower())
Pothole(camel)
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)
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);
}
}
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 이 출력되었습니다.
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();
}
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'))
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'))
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]));
}
}
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="")
s=input()
result=''
for i in s:
if i.isupper() or i.isnumeric:
result+='_'+i.lower()
else:
result+=i
print(result)
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)
자바로 풀어봤습니다.
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);
```
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)
# 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)
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());
}
}
}
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
다른분들에 비해 복잡하네요;
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)
// 명명 방식 변경 - 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);
}
}
}
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(""));
문자열의 제일 앞은 적용하지 않았습니다.
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'))
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;
}
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);
}
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);
}
}
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
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로 처리가 불가능한지?
Python으로 작성해봤습니다.
def to_pothole_case(s):
return ''.join(map(lambda x: '_' + x.lower() if x.isupper() or x.isdigit() else x, s)).lstrip('_')
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();
}
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 순서로 답을 구해나갔습니다.
첫번째 문자가 대문자일 경우, 단어 사이에 띄어쓰기가 있을 경우 모두 고려했습니다. 감사합니다.
파이썬 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)
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));
}
}
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"));
}
}
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]);
}
}
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;
}
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);
}
}
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')
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());
}
}
# 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"))
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);
}
# 한글 처리 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]))
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'))
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입니다 첫글자는 뼤고 적용하도록 짜봤습니다.
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)
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()
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))
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)
# 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)
자바
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);
}
}
파이썬
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
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' 등을 비교하는 식으로 가도 될 것 같네요
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)
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)
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'))
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")
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
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())
자바입니다!
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();
}
}
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]);
}
}
}
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))
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입니다. 위에보니까 훨씬 직관적으로 하신분들 많네요...
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)
멋지지는 않지만 남겨 봅니다.^^;
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"))
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
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");
}
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)
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);
} // 자바입니다. 엄청 더럽게 풀었네요
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;
}
}
# 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))
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
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))
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)
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())
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)
camele = 'python36CodingDojang'
pothole = ''
for i in camele:
if i.isupper() or i.isdigit(): pothole+='_'+i.lower()
else: pothole+=i
print(pothole)
import re
conv = lambda x:re.sub('[A-Z0-9]', lambda m:"_"+m.group().lower(),x)
print(conv("testEserThink093"))
파이썬입니다.
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())
#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);
}
const verifyCamelCase = name => {
let verifiedName = ''
for (let char of name) {
isRegSuccess = /[0-9A-Z]/.test(char)
isRegSuccess
? verifiedName += '_' + char
: verifiedName += char
}
return verifiedName
}
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')
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
파이썬 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))
// ============================================
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);
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)
import re
def camel_to_pothole2(str1):
p = re.compile("([A-Z0-9])")
m = p.sub("_\g<1>", str1)
return m.lower()
정규 표현식을 활용한 풀이 방법입니다. 아직 많이 부족하네요...
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))
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)
word = 'ParkJongHyuk95'
result = ''
for x in word:
if x.isupper() or x.isdigit():
result += '_'
result += x.lower()
print(result[1:])
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'))
strexample = input('문자열을 입력하세요. : ')
strre= ''
for x in strexample :
if x==x.upper() :
strre += '_' + x.lower()
else :
strre+=x
print(strre)
def Pothole(camel):
pothole = ""
for char in camel:
if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789":
pothole += "_" + char.lower()
else:
pothole += char
print(pothole)
Pothole(input("카멜케이스 입력 : "))
#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;
}
# 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'))
def pothole(string):
return ''.join('_' + x.lower() if x.isupper() or x.isdecimal() else x for x in string)
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')
CamelCase = list(input())
for number, i in enumerate(CamelCase):
if not i.islower():
i = i.lower()
CamelCase.insert(number, '_')
print(''.join(CamelCase))
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))
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)
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'))
javascript풀이 입니다.
파이썬과 같은 몇몇 프로그래밍 언어는 Pothole_case 를 더 선호하는 언어라고 합니다.
Example:
codingDojang --> coding_dojang
numGoat30 --> num_goat_3_0
위 보기와 같이 CameleCase를 Pothole_case 로 바꾸는 함수를 만들어요!
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'
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')
var input = 'codingDojang';
var result = input.replace(/[A-Z0-9]/g, function (a, b, c) {
return '_' + a.toLowerCase();
});
console.log(result);
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)
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))
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);
}
}
}
def pothole_case(string):
anw = ''
for i in string:
if i.isupper() or i.isnumeric():
anw += ('_'+str(i.lower()))
else:
anw += i
return anw
import re
def camel_to_pothole(s):
return re.sub('[A-Z0-9]', lambda m : '_' + m.group(0).lower(), s)
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)
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
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'))
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
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);
}
}
파이썬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
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)
#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");
}
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....')))
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()
def convert(n) :
res =""
for x in n:
if x.isupper() or x. isdigit():
x = "_" + x.lower()
res += x
return res
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)
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)
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)
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);
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)
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")
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)
def pothole(str1):
str2=''
for char in str1:
if char.isdigit() or char.isupper():
str2+="_"
str2+=char
return str2.lower()
print(pothole("numGoat30"))
catxt = 'codingDjango3'
potxt = ''
for i in catxt:
if i.isupper() or i.isdigit():
potxt += '_' + i.lower()
else:
potxt += i
print(potxt)
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')
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;
}
}
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
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')
#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')
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))
첫 번째 대문자는 패스했습니다.
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)
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())
_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("")
a = 'numGoat30'
for i in a:
if i.isupper() or i.isdigit():
print('_'+i.lower(), end='')
else:
print(i, end='')
깔끔하게 쓴 것 같습니다 ㅎ
title=input('CameleCase : ')
key1='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
for s in title:
if s in list(key1):
title=title.replace(s,"_"+s)
print(title.lower())
#두뇌의 한계 ..
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='')
string = str(input("camelCase를 입력하세요"))
print("".join([i if i.islower() or j == 0 else "_"+i.lower() for j,i in enumerate(string)]))
깔끔하게 한줄코딩! 첫글자가 대문자일때도, 숫자일때도 모두 커버합니다.