[백준 28637] Смена стиля (C#, C++) - soo:bak
작성일 :
문제 링크
설명
CamelCase 또는 camelCase로 된 변수명을 snake_case로 바꾸는 문제입니다.
접근법
문자열을 왼쪽부터 순회하며 대문자를 만날 때마다 앞에 언더스코어를 붙이고 소문자로 바꿉니다.
단, 첫 글자가 대문자인 경우에는 언더스코어 없이 소문자로만 변환합니다.
Code
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
using System.Text;
class Program {
static void Main() {
var n = int.Parse(Console.ReadLine()!);
for (var i = 0; i < n; i++) {
var s = Console.ReadLine()!;
var sb = new StringBuilder();
for (var j = 0; j < s.Length; j++) {
var ch = s[j];
if (ch >= 'A' && ch <= 'Z') {
if (j > 0) sb.Append('_');
sb.Append((char)(ch - 'A' + 'a'));
} else sb.Append(ch);
}
Console.WriteLine(sb.ToString());
}
}
}
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n; cin >> n;
for (int i = 0; i < n; i++) {
string s; cin >> s;
string res;
for (int j = 0; j < (int)s.size(); j++) {
char ch = s[j];
if (ch >= 'A' && ch <= 'Z') {
if (j > 0) res.push_back('_');
res.push_back(ch - 'A' + 'a');
} else res.push_back(ch);
}
cout << res << "\n";
}
return 0;
}