모든 짝수번째 숫자를 * 로 치환하시오.(홀수번째 숫자,또는 짝수번째 문자를 치환하면 안됩니다.) 로직을 이용하면 쉬운데 정규식으로는 어려울거 같아요.
Example: a1b2cde3~g45hi6 → a*b*cde*~g4*hi6
230개의 풀이가 있습니다.
True, False 가 리스트의 인덱스로 쓰일경우 각각 1,0으로 변환된다는 점을 이용하였습니다.
s = 'a1b2cde3~g45hi6'
print ''.join([[s[i],'*'][i&1==1 and s[i].isdigit()] for i in range(len(s))])
import re
print(re.sub(r'((.\D)*)(.)\d((.\D)*)', r'\1\3*\4', 'a1b2cde3~g45hi6'))
# 수정
import re
print(re.sub(r'((((.\D)*)(.)\d((.\D)*))|(.{2}))', lambda x: x.group(8) if x.group(8) else x.group(3) + x.group(5) + '*' + x.group(6), 'a1b2cde3~g45hi6'))
Python 3.5.2에서 작성하였습니다.
SOUP님 글을 보고 수정했습니다. 감사합니다.^^;
간단하게 생각해서 짜봤습니다 ㅋㅋ Java입니다
뭐 간단합니다
String으로 입력을 받은 후, char c[입력글자수] 배열을 만들어서 한글자씩 집어넣습니다
집어넣으면서 짝수(0부터 시작하므로 i%2==1)번째가 char형 숫자'0'~'9'이면 '*'를 대입합니다
package h_everyotherdigit;
import java.util.Scanner;
public class Every_other_digit {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String s=in.next();
int L=s.length(), i;
char[] c=new char[L];
for(i=0;i<L;i++){
c[i]=s.charAt(i);
if(i%2==1){
switch(c[i]){
case'0': case'1': case'2': case'3':case'4': case'5': case '6': case '7': case '8': case '9':
c[i]='*'; break;
}
}
System.out.print(c[i]);
}
}
}
#실행예시
d12abc3wf98we8fe23jh522fk23hf329f2face32fao325l23
d*2abc3wf*8we*fe2*jh5*2fk*3hf*2*f*face3*fao*2*l*3
c[]={'0','1', ... , '9'}일 때, (int)c[i]를 알아보니까,
48 49 50 51 52 53 54 55 56 57 이더군요
(즉, char형 숫자('0'~'9')의 int값은 그 숫자에 +48을 한 것입니다)
따라서, (int n;) n=(int)c[i]; →if(n>=48 && n<=57)이면 이 char형 c[i]는 숫자값을 가지고 있는 것입니다.
다시 짜봤습니다. 실행결과는 위와 같았습니다.
package h_everyotherdigit;
import java.util.Scanner;
public class Every_other_digit {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String s=in.next();
int L=s.length(), i, n;
char[] c=new char[L];
for(i=0;i<L;i++){
c[i]=s.charAt(i);
n=(int)c[i];
if(i%2==1 && n>=48 && n<=57) c[i]='*';
System.out.print(c[i]);
}
}
}
정규식을 활용해봤습니다. 자바스크립트입니다.
문제의 조건을 다음과 같이 재구성해보았습니다.
1) 모든 짝수번째 숫자를 *로 치환한다.
2글자에 매치하는 정규식을 만들자. 문자열 길이가 홀수인 경우 맨 마지막 문자의 순서는 홀수이므로 1글자로 인식할것이다. 즉, 정규식 매치가 안될것이다.
2) 홀수번째 숫자, 또는 짝수번째 문자를 치환하면 안된다.
홀수번째는 아무 문자나 올수있지만 치환하면 안된다. 짝수번째는 아무 문자나 올수있지만 숫자만 치환한다.
그래서 정규식을 활용해서 뽑아보기로 했습니다. 정규식을 잘 다루는 편이 아니라서 조악하지만 잘 봐주세요 ^^
"a1b2cde3~g45hi6".replace(/.(?:([0-9])|[^0-9])/g, function (str, match) {
return !match ? str : str[0] + "*"
});
a*b*cde*~g4*hi6
정규식으로 해 볼려고 했는데.. 너무 어렵네요. ㅜㅜ
정규식은 포기하고 파이썬으로 만들어 봤습니다.
총 3가지 버전입니다.
1번
def everyOtherDigit(s):
r = ""
s = list(s)
for odd, even in zip(s[::2], s[1::2]):
if '0' <= even <= '9': even = "*"
r += odd+even
if len(s)%2: return r+s[-1]
else: return r
2번
def everyOtherDigit(s):
r = ""
for i, c in enumerate(list(s)):
if i%2 and '0' <= c <= '9': r+="*"
else: r+=c
return r
3번
def everyOtherDigit(s):
s = list(s)
for i, c in enumerate(s):
if i%2 and '0' <= c <= '9': s[i]="*"
return "".join(s)
clojure
(apply str (for [[i c] (map-indexed vector "a1b2cde3~g45hi6")]
(if (and (zero? (mod (inc i) 2))
(Character/isDigit c))
\*
c)))
String text = "a1b2cde3~g45hi6";
StringBuilder value = new StringBuilder();
for(int i=0; i<text.length(); ++i) {
String add = "";
char t = text.charAt(i);
if(0 != i && i%2 != 0) {
if(t > 47 && t < 58) {
add = "*";
} else {
add = String.valueOf(t);
}
} else {
add = String.valueOf(t);
}
value.append(add);
}
Ruby
def every_other_digit(target)
target.scan(/./).map.with_index{|c,i|i%2==1 && c=~/[0-9]/?"*":c}.join
end
Test
require 'test/unit'
extent Test::Unit::Assertions
assert_equal every_other_digit("a1b2cde3~g45hi6"), "a*b*cde*~g4*hi6"
str='a1b2cde3~g45hi6'
strlen=len(str)
for i in range(0,strlen):
if i % 2 == 1 and str[i]<='9' and str[i]>='0':
str_c=str.replace(str[i],'*')
str=str_c
print(str)
파이썬입니다.
import re
data = "a1b2cde3~g45hi6"
list_data = list(data)
for num in range(len(list_data)):
if num % 2 <> 0:
patturn = re.compile(r"\d")
list_data[num] = patturn.sub("*", list_data[num])
print "".join(list_data)
결과 입니다.
a*b*cde*~g4*hi6
파이썬3
input_list = list('a1b2cde3~g45hi6')
output_str = ''
for idx, val in enumerate(range(0, len(input_list))):
if idx % 2 != 0:
if input_list[idx].isdigit():
input_list[idx] = '*'
output_str += str(input_list[idx])
print(output_str)
예전에 잠깐 배운 정규표현식으로 작성해보았습니다.
#!/usr/bin/env python
# a1b2cde3~g45hi6 -> a*b*cde*~g4*hi6
import re
def main():
origin_str = "a1b2cde3~g45hi6"
str_list = list(origin_str)
print origin_str
for i in range(1,len(origin_str),2):
str_list[i] = re.sub(r"\d", "*", str_list[i])
origin_str = "".join(str_list)
print origin_str
if __name__ == "__main__":
main()
아래는 정규표현식 안쓰고 작성한 버전 (문자열 크기 비교로 작성하였습니다.)
#!/usr/bin/env python
# a1b2cde3~g45hi6 -> a*b*cde*~g4*hi6
def main():
origin_str = "a1b2cde3~g45hi6"
str_list = list(origin_str)
print origin_str
for i in range(1,len(origin_str),2):
if str_list[i]>='0' and str_list[i]<='9':
str_list[i]='*'
str = "".join(str_list)
print str
if __name__ == "__main__":
main()
old_string = 'a1b2cde3~g45hi6'
new_string = ''
for i in range(len(old_string)):
if i % 2 is 1 and old_string[i].isdigit():
new_string += '*'
else:
new_string += old_string[i]
print new_string
이 문제는 설명은 따로 필요하지않을것같네요 코드가 가장 쉬운 설명같습니다.
package algorithms.level2.ing;
public class EveryOneDigit2 {
// 짝수번째 숫자를 *로 치환
// Example: a1b2cde3~g45hi6 → a*b*cde*~g4*hi6
public static void main(String[] args) {
String data = "a1b2cde3~g45hi6";
String replaceDigit = replaceDigit(data);
System.out.println(replaceDigit);
}
private static String replaceDigit(String data) {
StringBuffer stringBuffer = new StringBuffer();
for(int i=0; i<data.length(); i++){
char charAt = data.charAt(i);
if(i % 2 != 0){
if(Character.isDigit(charAt)){
charAt = '*';
}
}
stringBuffer.append(charAt);
}
return stringBuffer.toString();
}
}
두번째
public class EveryOtherDigit {
public static void main(String args[]){
String text = "a1b2cde3~g45hi6";
String replace = "";
for(int i=0; i<text.length();i++){
char charAt = text.charAt(i);
if(i % 2 != 0){
if(Character.isDigit(charAt)){
charAt = '*';
}
}
replace += charAt;
}
System.out.print(text + " -> " + replace);
}
}
#include <iostream>
using namespace std;
char* str = "a1b2cde3~g45hi6";
void main()
{
for(int i = 0; i < strlen(str); i++) {
if(str[i] >= '0' && str[i] <= '9' && (i+1) % 2 == 0) {
cout << "*" ;
} else {
cout << str[i];
}
}
cout << endl;
}
C++이 조금 가미된 C스타일의 코드입니다
print "teset"
print "가나"
str = "a123df4sdfd5sfdsfdsf"
def StringTo(Str,ch):
re =1 # switch
result=""
for i in Str:
re *=-1
if re>0 and i.isdigit(): # 짝수일때
i=ch;
result +=i
# 문자를 하나씩 추가하되 짝수이면 *로 홀수이면 그대로
return result
print(str)
str = StringTo(str,"*")
print(str)
파이썬 3.4 입니다.
def digit_transform(data):
result = ""
for x in range (0,len(data)):
temp_charac = data[x]
if temp_charac.isdigit() == True and x%2 == 1:
temp_charac = "*"
else:
pass
result = result + temp_charac
return result
data = input()
print(digit_transform(data))
자바 소스입니다~ String 형태를 char[]로 만든다음에 인덱스를 2개씩 증가하면서 체크했습니다.
package my_test;
/*
* 모든 짝수번째 숫자를 * 로 치환하시오.(홀수번째 숫자,또는 짝수번째 문자를 치환하면 안됩니다.)
* 로직을 이용하면 쉬운데 정규식으로는 어려울거 같아요.
* Example: a1b2cde3~g45hi6 → a*b*cde*~g4*hi6
*/
public class T {
public static void main(String[] args) {
String str="a1b2cde3~g45hi6";
System.out.println(change(str));
}
public static String change(String str){
char[] temp = str.toCharArray();
//아스키코드 48~57 : 0~9
for(int i=1;i<temp.length;i+=2){
if(48<=temp[i]&&temp[i]<=57){
temp[i]='*';
}
}
return String.valueOf(temp);
}
}
// C# 입니다.
using System;
using System.Collections.Generic;
class Program
{
static string input = "a1b2cde3~g45hi6";
static void Main()
{
char[] inputArray = input.ToCharArray();
for (var i = 1; i < inputArray.Length; i += 2)
{
int number;
if (Int32.TryParse(inputArray[i].ToString(), out number))
{
inputArray[i] = '*';
}
}
Console.WriteLine(input);
Console.WriteLine("---> " + new string(inputArray));
}
}
void Change(char* input) {
for(int i = 0; i < sizeof(input); i++) {
if(i%2 == 1 && (input[i] >= '0' && input[i] <= '9') ) {
printf("*");
}
else
printf("%c", input[i]);
}
}
// main.go
package main
import ("fmt"; "unicode";"strings")
func main() {
str := "a1b2cde3~g45hi6"
for index, runeValue := range str {
if unicode.IsDigit(runeValue) && index % 2 != 0 {
str = strings.Replace(str, string(runeValue), "*", -1)
}
}
fmt.Printf(str)
}
python 입니다.
import unittest
def func(arg):
x = ''
for i in range(len(arg)):
if i%2 == 1 and arg[i].isdigit() :
x = x + "*"
else :
x = x + arg[i]
return x
class CommaTest(unittest.TestCase):
def test1(self):
self.assertEqual('a*b*cde*~g4*hi6', func('a1b2cde3~g45hi6'))
if __name__ == "__main__":
unittest.main()
Scala
def everyOtherDigit(s:String) = {
s.map(c => if(c.isDigit && s.indexOf(c) % 2 == 1) '*' else c).mkString
}
coding by python beginner
t0 = 'a1b2cde3~g45hi6'
for i in range( len(t0) ):
if (i+1) % 2 == 0 and t0[i].isdigit():
t0 = t0[:i] + '*' + t0[i+1:]
print(t0)
Using python
import re
a = "a1b2cde3~g45hi6"
a= list(a)
for i in range(1,len(a),2):
a[i] = re.sub("\\d","*",a[i])
print "".join(a),
#데이터
string = "a1b2cde3~g45hi6"
src = list(string)
#처리
def change(src):
for s_char in range(1, len(src), 2):
if src[s_char].isnumeric():
src[s_char] = "*"
return "".join(src)
#입출력
print(change(src))
C#으로 작성했습니다.
using System.Text;
public string PrintConvertedEventhDigit(string input)
{
var output = new StringBuilder();
for (int i = 0; i < input.Length; i++)
{
var curr = input[i];
if (i%2 == 1 && char.IsDigit(curr)) output.Append('*');
else output.Append(curr);
}
return output.ToString();
}
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main()
{
char ss[] = "a1b2cde3~g45hi6";
int i;
for(i=0; i<strlen(ss); i++){
if((i % 2) == 1 && isdigit(ss[i])){
ss[i] = '*';
}
}
printf("%s\n", ss);
return 0;
}
string = "a1b2cde3~g45hi6"
def number( value ):
try :
int( value )
return "*"
except ValueError:
return value
def EveryOtherDigit( string ):
string2 = ""
for i in range(len(string)):
if i%2 == 1.0:
string2 += number( string[i] )
else : string2 += string[i]
return string2
print EveryOtherDigit( string )
#include <iostream>
using namespace std;
int main(){
char s[] = "a1b2cde3~g45hi6";
int size = sizeof(s) / sizeof(s[0]);
cout << s << endl;
for(int i=0;i<size;i++)
if((s[i]>47&&s[i]<58)&&!((i+1)%2)) s[i]='*';
// 짝수번째 인덱스의 문자가 0~9 사이일경우 (아스키코드 48~57 사이) *로 치환
cout << s << endl;
return 0;
}
Python 2
str = 'a1b2cde3~g45hi6'
lst = list(str)
replaced_by_ch = '*'
for x in lst:
i = lst.index(x) + 1
if i % 2 == 0:
if x >= '0' and x <= '9':
lst[i-1] = replaced_by_ch
void main() {
char inputStr[20] = {0,};
int i;
printf("입력 : ");
scanf("%s", inputStr);
printf("입력된 문자열 : %s \n", inputStr);
for(inputStr[i]; inputStr[i] != NULL; i++) {
if(inputStr[i] >= '0' && inputStr[i] <= '9')
if(inputStr[i] % 2 == 0)
inputStr[i] = '*';
}
printf("변환된 문자열 : %s \n", inputStr);
}
public static string Answers(string Str)
{
string Result = "";
int StrLgh = Str.Length;
char[] StrC = new char[StrLgh];
for (int i = 0; i < StrLgh; i++)
{
if ((i+1) % 2 == 0 && Str[i] >= 48 & Str[i] < 58)
{
StrC[i] = '*';
}
else
{
StrC[i] = Str[i];
}
}
Result = new string(StrC);
return Result;
}
자바공부중인 아마추어입니다. 귀엽게 봐주세요 ㅎㅎ
일단 for문에서 i가 2씩증가하게만들어 짝수 인덱스를 바로바로불러왔구요요 문자의 인덱스는 0... 1.... 2... 3... 과같이 0부터 시작함으로, 위에 2씩증가하는 for문의 i를 -1 씩해주어 육안상 짝수번째 인덱스를 맞추어주었습니다.
숫자판별은.. 아스키코드(10진수)로 48이상 57이하면 숫자입니다. 그러므로 charAt으로 i-1번째 인덱스를 빼와 if조건문으로 위사항을 체크했구요 숫자라면,,, StringBuffer의 replace메소드로.. -> StringBuffer.replace(시작index, 끝index, 변경문자열) 해당인덱스의 문자를 *로 바꾸어주었습니다.
public class Main {
public static void main(String[] args) {
StringBuffer str = new StringBuffer("a1b2cde3~g45hi6");
for (int i = 2; i < str.length(); i += 2) {
if(str.charAt(i - 1) >= 48 && str.charAt(i - 1) < 58){ // 숫자판별
str.replace(i-1, i, "*"); }
}
System.out.println(str);
}
}
Sub Main()
Dim n As Integer
Console.WriteLine(String.Join("", Console.ReadLine.ToArray.Select(Function(c As Char) IIf(IsNumeric(c.ToString) And System.Threading.Interlocked.Increment(n) Mod 2 = 0, "*"c, c))))
End Sub
Sub Main()
Dim n As Integer
Console.WriteLine(String.Join("", Console.ReadLine.ToArray.Select(Function(c As Char) IIf(IsNumeric(c.ToString) And System.Threading.Interlocked.Increment(n) Mod 2 = 0, "*"c, c))))
End Sub
#include <stdio.h>
#include <string.h>
int main()
{
int i;
char S[10000];
scanf("%s", S+1);
for (i = 1; i <= strlen(S+1); i++)
{
if (i%2 == 0 && S[i] >= '0' && S[i] <= '9')
{
printf("%c", S[i]);
}
else
{
printf("%c", S[i]);
}
return 0;
}
#include <stdio.h>
#include <Windows.h>
#pragma warning(disable : 4996)
int main()
{
char str[100];
printf("Example : ");
scanf("%s",str);
for(int i=1; str[i] != NULL;i+=2 )
{
if(str[i] >= '0' && str[i] <= '9')
str[i] = '*';
}
printf("\n%s",str);
system("pause");
return TRUE;
}
def even_change(s):
"""
(str) -> (list) -> str
This function changes the even number to "*". It does not apply for
characters.
>>>even_change("a1b2cde3~g45hi6")
a*b*cde*~g4*hi6
"""
l = list(s)
for i in range (1, len(l), 2):
if l[i].isdigit():
l[i] = "*"
return "".join(l)
C입니다
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
int main(){
char temp[80];
char *a;
gets(temp);
a = (char *)malloc(strlen(temp)+1);
strcpy(a,temp);
for(int i=0;i<strlen(temp)+1;i++){
if(i%2==1){
if(isdigit(a[i])){
a[i]='*';
printf("%c",a[i]);
}
else printf("%c",a[i]);
}
else printf("%c", a[i]);
}
}
string input = "a1b2cde3~g45hi6";
for (int i = 0; i < input.Length; i++ )
if ((i + 1) % 2 == 0)
if (input[i] >= 48 & input[i] < 58)
input = input.Replace(input[i], '*');
Console.WriteLine(input);
우선 스캐너로 문자열을 입력받은후 입력받은 문자열을 문자배열에 집어넣고 반복문을사용해 문자배열의 사이즈만큼 반복하고 반복구간중 인덱스 코드를 2로나눳을경우 1이 뜨는경우(인덱스코드는 0부터 시작함)중 char형0~9가있으면 그문자대신 *을 넣고 그것을 출력하는식으로 만들어 봤습니다
package dojavn;
import java.util.Scanner;
public class dsa {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
String ta=sc.nextLine();
char [] s=ta.toCharArray();
for(int i=0;i<s.length;i++)
{
if(i%2==1){
if(s[i]>='0'&&s[i]<='9'){
s[i]='*';
}
}
System.out.print(s[i]+" ");
}
}
}
a ="a1b2cde3~g45hi6"
for i in range(len(a)):
if((i%2)==1) & a[i].isdigit() :
print('*',end='')
else:
print(a[i],end='')
a에 문자 입력한후 i를 증가시키면서 a의 길이만큼 반복 i는 0부터 시작하므로 i가 홀수(짝수번째 문자)이고 a[i]번째 문자가 숫자이면 *을 출력 i가 짝수이거나(홀수번째 문자이거나) a[i]번째 문자가 숫자가 아니라면 그대로 출력
def dit(s):
r=0
s = list(s)
for k in range(0,len(s)) :
if s[k].isdigit():
r=r+1
if r%2==0:
s[k]='*'
return "".join(s)
파이썬입니다~~ ^^
s = "a1b2cde3~g45hi6"
l = list(s)
def aster( i ): l[i] = '*'
[ aster(i) for i in range(1, len(l), 2 ) if l[i].isdigit() ]
print ''.join(l)
void exce41()
{
char input[255];
int count = 0;
gets_s(input);
for (int i = 0; i < strlen(input); i++)
{
if (input[i] < '9' && input[i] > '0')
{
count++;
if (count % 2 == 0)
input[i] = '*';
}
}
printf("%s", input);
}
그냥 무난하게 해 봤습니다.
import java.util.Scanner;
public class EveryOtherDigit {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
String result = "";
for (int i = 0;i<input.length();i++){
if(i == 0 || i%2 == 0)
result = result + input.charAt(i);
else {
if(input.charAt(i)>=48 && input.charAt(i)<=57)
result = result + "*";
else
result = result + input.charAt(i);
}
}
System.out.println(result);
}
}
thestring = input(); thestring = list(thestring)
for i in range(0, len(thestring)-1):
if i%2 == 1:
thestring[i] = '*'
thestring = "".join(thestring); print(thestring)
입력받은 문자열을 리스트로 변환한 후, 홀수 번째 항을 '*'으로 치환한 뒤 다시 단일 문자열로 재변환하여 출력합니다.
def replace_with_asterisk(text):
text_list = list(text)
for i, c in enumerate(text):
if i % 2 == 1 and 48 <= ord(c) <= 57:
text_list[i] = '*'
return ''.join(text_list)
public class substitute implements baseInterface {
@Override
public void init() {
System.out.println("아무 문제나 입력 : ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println(str);
char[] temp = new char[100];
int lengthStr = str.length();
for (int i = 0; i < lengthStr; i++) {
char c = str.charAt(i);
temp[i] = c;
if((i+1)%2 == 0){
if(c<48 || c> 57){ // 문자인 경우
temp[i] = '*';
}
}
}
str = "";
for (int i = 0; i < lengthStr; i++) {
str += temp[i];
}
System.out.print(str);
}
}
파이썬입니다.
def convert_to_star(string):
listed_string = list(string)
for i in range(1, len(listed_string), 2):
if listed_string[i].isdigit():
listed_string[i] = '*'
return ''.join(listed_string)
print(convert_to_star("a1b2cde3~g45hi6"))
<?php
echo encode('a1b2cde3~g45hi6');
function encode($str)
{
for ($i=0; $i < strlen($str); $i++) {
if ($i != 0 && $i%2 == 1) {
if(is_numeric($str[$i])) $str[$i] = '*';
}
}
return $str;
}
?>
파이썬 2.7
s = 'a1b2cde3~g45hi6'
s = s.replace('', ' ').split()
result = ''
for i in range(len(s)):
if i % 2 != 0 :
result += '*'
else:
result += s[i]
print result
파이썬 2.7.11
import string
s = 'a1b2cde3~g45hi6'
s = s.replace('', ' ').split()
result = ''
for i in range(len(s)):
if i % 2 != 0 and s[i] in string.digits:
result += '*'
else:
result += s[i]
print result
s="a1b2cde3~g45hi6"# → a*b*cde*~g4*hi6"
outS=''
for idx,c in enumerate(s):
if c.isdigit() and (idx+1)%2==0:
outS+='*'
else:
outS+=c
print outS
숫자인지 문자인지 구분하는 법이 생각이 나지않아 숫자리스트를 구성한 뒤, 숫자가 리스트에 있으면 "*"을 붙이는 방식으로 하였습니다.
def change(input1):
listb=[]
listc=['1','2','3','4','5','6','7','8','9','0']
for i in range(0,len(input1)):
if i%2 !=0:
if input1[i] in listc:
listb.append("*")
else:
listb.append(input1[i])
else:
listb.append(input1[i])
return "".join(listb)
input1 ='a1b2cde3~g45hi6'
print change(input1)
Ruby
convert = ->s{ s.chars.each_index.map{|i|i.odd?&&s[i].to_i>0?"*":s[i]}.join }
개선
convert = ->s{ s.chars.map.with_index{|v,i|i.odd?&&v.to_i>0?"*":v}.join }
Test
expect(convert["a1b2cde3~g45hi6"]).to eq "a*b*cde*~g4*hi6" # true
s = raw_input("input a string of numbers:")
ls = []
for i in s:
ls.append(i)
for i in range(len(ls)):
if i%2 != 0:
ls[i] = "*"
print "".join(ls)
#coding: CP949
data=input('입력하라: ') # 문자 데이터 입력
data_list=list(data) # 문자를 리스트로 전환
i=1
while i<=len(data_list)-1: # while문은 짝수번째 문자에만 접근하여 *로 바꾸는 과정
try:
if type(int(data_list[i])) == type(1):
data_list[i] = "*"
i+=2
except:
i+=2
continue
output=""
for i in data_list: # data_list를 문자로 전환하여 출력
output+=i
print(output)
파이썬 초짜 올려봐요~
python 3.5
def change_string(string):
string = list(string)
for x in range(len(string)):
if x % 2 == 1 and string[x].isdigit():
string[x] = '*'
return ''.join(string)
print(change_string('a1b2cde3~g45hi6'))
void evenToStar(String s) {
for(int i=0; i<s.length(); i++) {
char index = s.charAt(i);
if(i%2 == 1 && (int)index >= 48 && (int)index <= 57) {
index = '*';
}
System.out.print(index);
}
}
java
일반:
while __name__ == '__main__':
inpt = input('입력 ')
print(''.join(list(inpt[x] if x%2 == 0 else '*' for x in range(len(inpt)))))
정규식:
import re
while __name__ == '__main__':
inpt = input('입력: ')
for x in re.compile('([^\*]).').finditer(inpt):inpt = inpt[:x.start()+1]+'*'+inpt[x.start()+2:]
print(inpt)
파이썬 3.4입니다.
a = 'a1b2cde3~g45hi6'
for i in range(len(a)):
if i % 2 == 1 and a[i].isnumeric():
print('*', end = '')
else:
print(a[i], end = '')
# 2016-10-27
print(''.join('*' if s[i].isdigit() and (i+1)%2==0 else s[i] for i in range(len(a))))
다음에 정규식으로도 풀어봐야겠네요, 지금은 이게 더 쉬운 듯한..
String input = "a1b2cde3~g45hi6";
StringBuffer sb = new StringBuffer(input);
for(int i = 0 ; i <input.length() ;i++){
if(i%2 == 1 && (sb.charAt(i) >= '0' && sb.charAt(i)<='9') ) //짝수 번째
sb.setCharAt(i, '*');
}
System.out.println(sb.toString());
#파이썬3.5.1
def do(s):
s = (' '.join(s)).split()
for i in range(1,len(s),2):
if s[i] in [str(x) for x in range(10)]:
s[i] = '*'
return ''.join(s)
print(do(input()))
python 3.4.4
data = list('a1b2cde3~g45hi6')
for i in range(1, len(data), 2):
if data[i].isdigit():
data[i] = '*'
print("".join(data))
간단히 구현했는지 맞는지 모르겠네요
#include <stdio.h>
#include <string.h>
#pragma warning(disable:4996)
int main()
{
char a[]="a1b2cde3~g45hi6";
int size;
size=strlen(a);
for(int i=1;i<size;i+=2)
if(a[i]>'/'&&a[i]<':') a[i]='*';
printf("%s\n",a);
}
words = "a1b2cde3~g45hi6"
for indexNum in range(len(words)-1):
if 48 <= ord(words[indexNum]) <= 57:
if indexNum % 2 == 1:
words = words[:indexNum] + "*" + words[indexNum+1:]
print words
public class lv2_17 {
public static void main(String[] args) {
String str = "a1b2cde3~g45hi6";
for(int i = 0 ;i < str.length();i++){
if(str.charAt(i)>='0'&&str.charAt(i)<='9'&&i%2==1) System.out.print("*");
else System.out.print(str.charAt(i));
}
}
}
void exchanger(char *string)
{
for (int i = 0; *(string + i) != NULL; i++)
if (i % 2 == 1 & *(string + i) >= '0' & *(string + i) <= '9')
*(string + i) = '*';
}
string inputstr = "a1b2cde3~g45hi6";
string newstr = new String(inputstr.Select((k, i) => i % 2 != 0 && (k > 48 && k < 57) ? '*' : k).ToArray());
Console.WriteLine($"{inputstr} => {newstr}");
int main() { char str[256]; int i; fgets(str, sizeof(str), stdin); str[strlen(str)-1] = '\0'; for (i = 1; i < strlen(str); i+=2) { if ((str[i] < 48) || (str[i] > 57)) continue; str[i] = '*'; } printf("%s\n", str);
return 0;
}
def func(string):
for x in range(1,len(string),2):
if string[x].isnumeric():
string = string[:x] + '*' + string[x+1:]
return string
#### 2016.12.29 D-420 ####
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main() {
char str[] = "a1b2cde3~g45hi6";
for(int i=0;i<strlen(str);i++) {
if((i+1)%2==0 && str[i] >= 48 && str[i] <= 57)
str[i] = '*';
}
printf("%s", str);
}
public class Test428 {
public static void main(String[] args) {
StringBuffer strb = new StringBuffer("a1b2cde3~g45hi6");
for (int i = 1; i < strb.length(); i += 2) {
if (isNumber(strb.charAt(i) + "")) {
strb.setCharAt(i, '*');
}
}
System.out.println(strb);
}
public static boolean isNumber(String num) {
try {
double d = Double.parseDouble(num);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
}
a*b*cde*~g4*hi6
def star(data):
data=list(data)
A="0123456789"
return ''.join(['*' if i%2==1 and data[i] in A else data[i] for i in range(len(data))])
star("a1b2cde3~g45hi6")
#include <iostream>
#include <string>
using namespace std;
int main()
{
int strToNum, size; //strToNum: str의 문자를 정수형으로 변환한 값을 할당하기위한 변수, size: str의 사이즈를 저장하기위한 변수//
string str = "a1b2cde3~g45hi6";
size = str.size();
cout << str << endl;
for (int i = 0; i < size; i++) {
strToNum = str.at(i);
if (i % 2 != 0 && strToNum <= 57 && strToNum >= 48)
str.at(i) = '*';
}
cout << str << endl;
return 0;
}
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
* URL : http://codingdojang.com/scode/428
* URL : http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html Groups and capturing
* */
public class EveryOtherDigit {
public static void main(String[] args) {
String i = "a1b2cde3~g45hi6";
String[] r = i.split("");
Pattern p = Pattern.compile("\\d");
Matcher m = p.matcher(i);
while (m.find()) {
if (m.start() % 2 != 0) r[m.start()] = "*";
}
System.out.println(String.join("", Arrays.asList(r)));
}
}
def eod(s):
return ''.join(['*' if (i+1) % 2 == 0 and '0' <= s[i] <= '9' else s[i] for i in range(len(s))])
print(eod('a1b2cde3~g45hi6'))
package training;
/**
* 모든 짝수번째 숫자를 * 로 치환하시오.(홀수번째 숫자,또는 짝수번째 문자를 치환하면 안됩니다.)
* Example: a1b2cde3~g45hi6 → a*b*cde*~g4*hi6
*/
public class EveryOtherDigit {
public static void main(String[] args) {
String str = "a1b2cde3~g45hi6";
char[] ch = str.toCharArray();
StringBuffer sf = new StringBuffer();
for(int i=0;i<ch.length;i++){
if((i+1)%2 == 0){ // 짝수일 경우
if(ch[i] == '0' || ch[i] == '1' || ch[i] == '2' || ch[i] == '3' || ch[i] == '4'
|| ch[i] == '5'|| ch[i] == '6' || ch[i] == '7' || ch[i] == '8' || ch[i] == '9')
{
sf.append("*");
} else {
sf.append(ch[i]);
}
} else { // 홀수일 경우
sf.append(ch[i]);
}
}
System.out.println(sf);
}
}
y=list("a1b2cde3~g45hi6")
for i in range(len(y)):
if (i-1)%2==0 and y[i].isdigit()==True :
y[i]="*"
result="".join(y)
print(result)
var input = "a1b2cde3~g45hi6";
// regular expression with callback
var result = input => input.replace(/.\D|.(\d)/g, (s,d) => d ? s[0] + "*" : s);
console.log(result1(input));
정규표현식으로 잘 안풀리네요;; 풀이를 보기 전에 단순한 방법으로 작성한 코드를 올립니다.
def replace_even_number(s):
new_s = ''
for i in range(0, len(s)):
if i % 2 is not 0 and s[i].isdigit():
new_s += '*'
else:
new_s += s[i]
return new_s
정규표현식으로 풀었습니다. 'aa1'과 같은 경우에는 변경이 없어야 합니다.
2칸씩 match하면서 '그룹2'가 있으면 ('그룹1' + '그룹2')로, 없으면 ('그룹1' + '*')로 변환합니다.
import re
def replace_even_number(s):
repl=lambda m: m.group(1) + (m.group(2) if m.group(2) else '*')
return re.sub(r'(.)(?:\d|(\D))', repl, s)
def numtosc(string) :
listedstring = list(string)
number_list = []
for i in range(0, 10):
number_list.append(str(i))
for n in range(1, len(string), 2) :
if listedstring[n] in number_list :
listedstring[n] = '*'
return ''.join(listedstring)
string_input = input("any string with alphabet, number, and special characters : ")
print(numtosc(string_input))
def changeNum(str):
for idx, chr in enumerate(str):
if (idx+1)%2 == 0 and chr.isdigit():
str = str.replace(chr, '*', 1)
print(str)
changeNum('a1b2cde3~g45hi6')
/**
* @author : 염현우
* @date :2017. 9. 8.
* @description :
* 모든 짝수번째 숫자를 * 로 치환하시오.(홀수번째 숫자,또는 짝수번째 문자를 치환하면 안됩니다.)
* 로직을 이용하면 쉬운데 정규식으로는 어려울거 같아요.
* Example: a1b2cde3~g45hi6 → a*b*cde*~g4*hi6
*
*/
public class Ex9 {
public static void main(String[] args) {
String data = "a1b2cde3~g45hi6";
StringBuilder result = new StringBuilder();
for(int i=0;i<data.length();i++) {
if(i%2 == 0) {
result.append(data.charAt(i));
continue;
}
if(Character.isDigit(data.charAt(i))) result.append("*");
else result.append(data.charAt(i));
}
System.out.println(result);
}
}
package codingdojang;
import java.util.Scanner;
public class ex41 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
String temp = sc.nextLine();
int count = 0;
boolean num = false;
char arr[] = temp.toCharArray();
for(int i=0; i < arr.length; i++) {
num = false;
if('0' <= arr[i] && arr[i] <= '9') {
count++;
num = true;
}
if(count%2==0 && num == true) {
arr[i] = '*';
}
}
System.out.println(arr);
}
}
char = "a1b2cde3~g45hi6"
new=""
i=0
for ch in char :
i +=1
if i%2==0 and ch.isdigit(): ch = "*"
new = new + ch
new
python 3.5.2 입니다.
import re
a = raw_input("enter something: ")
p = re.compile('\d')
c = []
for i in range(len(a)):
m = p.match(a[i])
if (i+1) % 2 == 0 and m:
c.append("*")
else:
c.append(a[i])
print "".join(c)
sen=input()
for x,y in enumerate(sen[1::2]):
if y.isdigit():
sen=sen[:x*2+1]+'*'+sen[x*2+2:]
print(sen)
txt = list('a1b2cde3~g45hi6')
for i in range(0,len(txt),2): # 짝수만 받아오기 !!
if txt[i].isnumeric():
txt[i]='*'
print("".join(txt))
txt = list('a1b2cde3~g45hi6')
for i in range(0,len(txt),2): # 짝수만 받아오기 !!
if txt[i].isnumeric():
txt[i]='*'
print("".join(txt))
파이썬 3.6
data = 'a1b2cde3~g45hi6'
def change_even(data):
datalist = list(data)
for i, value in enumerate(datalist):
if (i+1)%2 == 0 and value.isdigit():
datalist[i] = '*'
print(data," -> ",''.join(datalist),"\n")
if __name__ == "__main__":
change_even(data)
*결과값
a1b2cde3~g45hi6 -> a*b*cde*~g4*hi6
# 파이썬
sample = "a1b2cde3~g45hi6"
def eod(str1):
n = 0
r = ""
for m in str1:
if n == 0:
n = 1
r += m
elif n == 1:
n = 0
if m in "1234567890":
r += "*"
return r
print(eod(sample))
def evendigit(n):
a = list(n)
for i in range(len(a)//2):
if a[2*i+1] in '0123456789':
a[2*i+1] = '*'
b = ''
for i in a:
b += i
return b
m = input()
print(evendigit(m))
import java.util.*;
public class Main { public static void main(String[] args) { Scanner scanf=new Scanner(System.in); String s=scanf.next();
char[] chr=s.toCharArray();
StringBuffer sb=new StringBuffer();
for(int i=1; i<chr.length; i=i+2) {
if(Character.isDigit(chr[i])) {
chr[i]='*';
}
}
for(int i=0; i<chr.length; i++) {
System.out.print(chr[i]);
}
}
}```{.java}
```
for_change_string=input("바꾸려는 문자열을 입력하세요\n")
len_for_change_string=len(for_change_string)
new_str=''
for k in range(len_for_change_string):
if k%2==1 and for_change_string[k].isdigit():
new_str+='*'
else:
new_str+=for_change_string[k]
print(new_str)
import re
def digit(string) :
p = re.compile('\d')
str_list = re.findall('.', string)
for i in range(1, len(str_list), 2) :
str_list[i] = p.sub('*', string[i])
print(''.join(str_list))
정규식으로 풀어봤습니다. 패턴객체를 if 조건처럼 활용해서 풀어봤어요.
def change(put):
result = ''
for n, char in enumerate(put):
if n%2 == 1:
try:
if int(char)*1 == int(char):
result = result + '*'
except: result = result + char
else: result = result + char
return result
Python 3
s = input("input: ")
n_s = []
for i in range(0,len(s)):
if i % 2 == 1:
if s[i] in '0123456789':
n_s.append('*')
else:
n_s.append(s[i])
else:
n_s.append(s[i])
print("".join(n_s))
import java.util.Scanner;
import java.util.regex.Pattern;
public class EveryOtherDigit {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
StringBuilder sb = new StringBuilder(input);
Pattern p = Pattern.compile("[0-9]");
for(int i=1; i< sb.length(); i=i+2){
if(p.matcher(sb.substring(i, i+1)).find()){
sb.replace(i, i+1, "*");
}
}
System.out.println(sb.toString());
}
}
Swift입니다. 정규식 없이 풀었습니다.
import Foundation
func translate(_ input: String) -> String {
var inputArray = Array(input)
for i in stride(from:1, to: inputArray.count, by: 2) {
if "0"..."9" ~= inputArray[i] {
inputArray[i] = "*"
}
}
return String(inputArray)
}
print( translate("a1b2cde3~g45hi6") )
// Every Other Digit
package main
import (
"fmt"
"strconv"
)
// cnvt: aString의 짝수번째 문자가 숫자일 경우 *로 치
func cnvt(aString string) string {
newString := ""
for i, v := range aString {
if _, err := strconv.Atoi(string(v)); i%2 == 1 && err == nil {
newString += "*"
} else {
newString += string(v)
}
}
return newString
}
func main() {
inpString := "a1b2cde3~g45hi6"
fmt.Println(cnvt(inpString))
}
def star(str):
for i in range(len(str)):
if i % 2 == 1 and str[i].isnumeric() == True:
str = str.replace(str[i],"*")
return str
print(star("a1b2cde3~g45hi6"))
import java.util.Scanner;
public class Dig{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String exaMple = sc.nextLine();
System.out.println("String 입력");
String arr[] = new String [exaMple.length()];
for(int i=0;i<exaMple.length();i++){
arr[i] = exaMple.charAt(i) + "";
if(Character.isDigit(exaMple.charAt(i)) && exaMple.indexOf(exaMple.charAt(i))%2!=0)
arr[i] = "*";
System.out.print(arr[i]);
}
System.out.println();
}
}
//자바입니다
public static void main(String[] args) throws Exception {
String str = "a1b2cde3~g45hi6";
StringBuffer sb = new StringBuffer(str);
for (int i=0; i<sb.length(); i++) {
if (i%2 == 1 && (48 <=sb.charAt(i) && sb.charAt(i) <= 57)) {
sb.setCharAt(i,'*');
}
}
System.out.println(sb);
} // 스트링버퍼의 메서드를 썻어요
user_input = input()
def Change_String(string):
result = ''
for index in range(len(string)):
if index % 2 == 0 :
result = result + string[index]
elif index %2 == 1 and not string[index].isnumeric():
result = result + string[index]
else:
if string[index].isnumeric():
result = result + '*'
return result
print(Change_String(user_input)) # a*b*cde*~g4*hi6
public class substitute implements baseInterface {
@Override
public void init() {
System.out.println("아무 문제나 입력 : ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println(str);
char[] temp = new char[100];
int lengthStr = str.length();
for (int i = 0; i < lengthStr; i++) {
char c = str.charAt(i);
temp[i] = c;
if((i+1)%2 == 0){
if(c<48 || c> 57){ // 문자인 경우
temp[i] = '*';
}
}
}
str = "";
for (int i = 0; i < lengthStr; i++) {
str += temp[i];
}
System.out.print(str);
}
}
public class EveryOtherDigit {
public static void main(String[] args) {
String str = "a1b2cde3~g45hi6";
for (int i = 1; i < str.length(); i += 2)
if (str.substring(i, i + 1).matches("^[0-9]$"))
str = str.replaceAll(str.substring(i, i + 1), "*");
System.out.println(str);
}
}
Python
test = "a1b2cde3~g45hi6"
ans = ""
for i, c in enumerate(test):
if (i+1)%2 == 0 and c.isdigit():#even index
ans += "*"
else:
ans += c
print(ans)
// 코딩연습
#include <stdio.h>
int main() {
char str[100];
scanf("%s",str);
for(int i=0; str[i]; i++) {
if(str[i]>='0' && str[i]<='9' && (i+1)%2==0) {
str[i]='*';
}
}
printf("%s\n",str);
}
a = "a1b2cde3~g45hi6"
print(''.join(['*' if (a[i].isdigit() and (i+1)%2 == 0) else a[i] for i in range(len(a))]))
import re
repl = lambda m: m.group(1) + (m.group(2) if m.group(2) else '*')
print(re.sub(r'(.)(?:\d|(\D))', repl, a))
s = 'a1b2cde3~g45hi6'
print(''.join('*' if i%2 and s[i].isdigit() else s[i] for i in range(len(s))))
import re
s = 'a1b2cde3~g45hi6'
print(re.sub('((..)+?)(.)\d',r'\1\3*',re.sub('(^(..)*?)(.)\d',r'\1\3*',s)))
파이썬3
def fn(s):
result = ""
digits = "0123456789"
for i, v in enumerate(s):
if i % 2 == 1 and v in digits:
result += "*"
else:
result += v
return result
input = "a1b2cde3~g45hi6"
print(fn(input))
결과
a*b*cde*~g4*hi6
import re
su=re.compile("\d") #숫자일경우
mun=re.compile("\D")#숫자가 아닐경우
data = 'a1b2cde3~g45hi6'
count =1
result = []
result2 =""
for i in data:
if count%2 ==1: #홀수번째
result.append(i)
elif count%2 ==0:#짝수번째
if su.match(i):#숫자일경우
i='*'
result.append(i)
elif mun.match(i): #문자일경우
result.append(i)
count+=1
for y in range(len(result)): #리스트 ->문자열
result2 += result[y]
print(result2)
#모든 짝수번째 숫자를 *로 치환하시오
def change (x):
x=list(x)
for i in range(1,len(x),2):
if x[i].isdigit()==True:
x[i]='*'
else:
pass
return ''.join(x)
print(change('12415123412341234512'))
C언어
#include<stdio.h>
#include<string.h>
int main()
{
char example[]="a1b2cde3~g45hi6";
int len;
int i;
len = strlen(example);
for(i=1; i<len; i=i+2)
{
if('9'>=example[i] && '0'<=example[i])
{
example[i] = '*';
}
}
for(i=0; i<len; i++)
{
printf("%c",example[i]);
}
}
def evennum(n):
n = list(n)
for x in n:
if x.isdigit() and (n.index(x)+1)%2 == 0:
n[n.index(x)] = '*'
print(''.join(n))
def fix(arr):
l = list(arr)
for i in range(len(l)):
if i % 2 == 1 and '0' < arr[i] < '9':
l[i] = '*'
print (''.join(l))
test = 'a1b2cde3~g45hi6'
fix(test)
C#
using System;
using System.Linq;
namespace CD041
{
class Program
{
static void Main()
{
string input = "a1b2cde3~g45hi6";
string result = new String(input.Select((v, i) => (i % 2 == 1 && Char.IsDigit(v)) ? '*' : v).ToArray());
Console.WriteLine(result);
}
}
}
s = 'a1b2cde3~g45hi6'
result = ''
for idx, i in enumerate(s):
if idx%2!=0:
if i.isdigit():
result = result + '*'
else:
result = result + i
else:
result = result + i
print(result)
import java.util.Scanner;
public class KimSanghyeop {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.print("문장을 입력하세요 : ");
String str = sc.nextLine();
char[] arr = str.toCharArray();
String res = "";
for(int f1=0;f1<arr.length;f1++)
{
if(f1 % 2 ==1 && arr[f1] >= '0' && arr[f1] <='9')
{
res+="*";
}
else
{
res+=arr[f1];
}
}
System.out.println(res);
}
}
def even_num_to_star(s):
l = list(s)
for i in range(1, len(l), 2):
if l[i].isdigit():
l[i] = '*'
return ''.join(l)
c언어 입니다.
int main() { char a= malloc(sizeof(char)254); strcpy(a, "a1b2cde3~g45hi6"); int size=strlen(a);
for(int i=0;i<size;i++){
if(i%2==1){
if(a[i]>=48 && a[i]<=57){
a[i]='*';
}
}
}
printf("%s", a);
}
string = input()
for i in string:
if i.isdigit() and string.find(i) % 2 != 0:
string = string.replace(i,'*')
print(string)
example = "a1b2cde3~g45hi6"
#a*b*cde*~g4*hi6
answer = list(example)
for idx in range(1,len(example),2):
if example[idx].isdigit():
answer[idx]="*"
print(''.join(answer))
ex = 'a1b2cde3~g45hi6'
out = ''
for i, ch in enumerate(ex):
if 0 != i % 2 and '0' <= ch and '9' >= ch:
out += '*'
else:
out += ch
print(out)
function change(input){
const splitted = input.split('')
const result = splitted.map((split,index)=>isNaN(Number(split))===false && index%2 ===1?split = '*':split = split)
return result.join('')
}
change('a1b2cde3~g45hi6')
in_str = input("입력: ")
for i in range(2,len(in_str),2):
if ord(in_str[i-1])>47 and ord(in_str[i-1])<58:
in_str = in_str[:i-1]+'*'+in_str[i:]
print(in_str)
a=list(input())
for x in range(len(a)):
if x%2==1:
try:
float(a[x])
a[x]='*'
except:
pass
else:
pass
print(''.join(a))
namespace codingdojang__
{
class Program
{
static void Main(string[] args)
{
Every_other_digit("a1b2cde3~g45hi6");
}
static void Every_other_digit(string input)
{
int temp;
for (int i = 0; i < input.Length; i++)
{
if ((i + 1) % 2 == 0 && int.TryParse(input[i].ToString(), out temp) == true)
{
input = input.Insert(i, "*");
input = input.Remove(i + 1, 1);
}
}
Console.WriteLine(input);
}
}
}
number='1234567890'
user=input("Input string: ")
for i in range(len(user)):
if i%2==1 and user[i] in number:
user=user[:i]+"*"+user[i+1:]
print(user)
def every_other_digit(string):
new = ""
for n, s in enumerate(string):
if (n+1) % 2 == 1:
new += s
if (n+1) % 2 == 0:
if s in "0123456789":
new += "*"
else:
new += s
print(new)
str=input("영어와 숫자를 입력하시오:")
sum=0
str_pos=[]
new_str=""
for x in str:
sum+=1
str_pos.append(x)
for x in range(0,sum):
if x%2==1:
if ord(str_pos[x])>=47 and ord(str_pos[x])<=59:
str_pos[x]='*'
for x in range(0,sum):
new_str+=str_pos[x]
print(new_str)
import java.util.Scanner;
public class EveryOtherDigit {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("문자를 입력하세요.");
String str = scanner.nextLine();
for(int i = 1; i < str.length(); i += 2) {
if(isnumber(str.substring(i, i + 1))) {
System.out.print(str.substring(i, i + 1) + " ");
}
}
}
public static boolean isnumber(String string) {
boolean result = false;
try {
Integer.parseInt(string);
result = true;
} catch (Exception e) { }
return result;
}
}
def chihwan(string):
lst = []
for ind_i,i in enumerate(string):
if ind_i % 2 == 1 and i in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
lst.append('*')
else:
lst.append(i)
return ''.join(lst)
a = 'a1b2cde3~g45hi6'
a = list(a)
res=''
for i in range(1,len(a),2):
if a[i] in '0123456789':
a[i]='*'
for j in a:
res += str(j)
print(res)
s=input();ans=''
for i in range(len(s)):
if ord('0')<=ord(s[i])<=ord('9'):
if (i+1)%2==0:
ans+='*'
else:
ans+=s[i]
else:
ans+=s[i]
print(ans)
a=input("문자열입력: ")
num=['0','1','2','3','4','5','6','7','8','9']
b=""
for i in a:
if a.index(i)%2==1 and i in num:
b=b+'*'
else:
b=b+i
print(b)
PHP
$str = 'a1b2cde3~g45hi6';
$arr = str_split($str);
foreach ($arr as $k => & $v) {
if ($k % 2) $v = preg_replace("/\d/", "*", $v);
}
$result = implode($arr);
print_r($result); // a*b*cde*~g4*hi6
def convert(str):
a = '0123456789'
lstStr = list(str)
for i in range(len(lstStr)):
if i % 2 == 1 and lstStr[i] in a:
lstStr[i] = '*'
return ''.join(lstStr)
print(convert('a1b2cde3~g45hi6'))
txt = "a1b2cde3~g45hi6"
for i in range(1,len(txt),2):
if 48 <= ord(txt[i]) <= 57 :
print(ord(txt[i]))
txt = txt[:i] + "*" + txt[i+1:]
print(txt)
python3
NUM = [str(i) for i in range(0, 10)]
def function(data):
out = ''
for i in range(0, len(data)):
if data[i] in NUM and (i+1)%2 == 0:
out += '*'
else:
out += data[i]
return out
data = 'a1b2cde3~g45hi6'
out = function(data)
print(out)
import java.util.*;
public class EveryOtherDigit {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String[] strs = scan.next().split("");
ArrayList<String> list = new ArrayList<String>();
for(int i=0; i<strs.length; i++) {
list.add(strs[i]);
}
for(int j=1; j<strs.length; j=j+2) {
try {
Integer.parseInt(strs[j]);
list.set(j, "*");
}
catch(NumberFormatException e){
}
}
String line = String.join("", list);//string arraylist를 변환하는 경우
System.out.println(line);
}
}
#include <iostream>
using namespace std;
char a[100];
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i];
for(int i=1;i<=n;i++)
if(i%2==0)
if(a[i]>=48 && a[i]<=57)
a[i]='*';
for(int i=1;i<=n;i++)
cout<<a[i];
}
파이썬 3.6 입니다
def replace_even_index_numbers(s):
s_list = list(s)
rst = []
for i in range(1, len(s_list), 2):
if s_list[i].isnumeric():
s_list[i] = "*"
return "".join(s_list)
print(replace_even_index_numbers("a1b2cde3~g45hi6"))
def digit(x):
y =list(x)
for i in range(1,len(y),2):
if y[i].isdigit():
y[i]='*'
return ''.join(y)
print(digit('a1b2cde3'))
재귀함수를 이용해서 값을 판별하는 방법과 반복문을 통해서 값을 판별하는 방법 이 2가지로 풀었습니다.
import java.util.Scanner;
public class DigitConverter {
public static void main(String[] args) {
int i = 0;
Scanner sc = new Scanner(System.in);
DigitConverter dc = new DigitConverter();
System.out.print("문자열을 입력하시오: ");
String str = sc.nextLine();
char[] array = dc.Swap(str);
dc.Converter1(array, i);
dc.Converter2(array);
sc.close();
}
//char[]에 값 저장하는 메소드
public char[] Swap(String str) {
char[] array = new char[str.length()+1];
for(int i = 0; i<str.length(); i++) {
array[i] = str.charAt(i);
}
array[str.length()]= '\0'; //char[] 마지막에 \0값 넣기
return array;
}
//재귀함수를 이용하여 값 판별하는 메소드
public void Converter1(char[] array , int i) {
if(array[i]=='\0') { //char[] 마지막일떄 메소드 종료
System.out.println();
return;
}
if((i%2==1) && (array[i]>= '0') && (array[i]<= '9')) { //짝수번째 숫자 *로 치환
array[i] = '*';
}
System.out.print(array[i]);
Converter1(array, i+1);
}
//반복문을 이용하여 값을 판별하는 메소드
public void Converter2(char[] array) {
for(int i =0; i<array.length; i++) {
if((i%2==1) && (array[i]>= '0') && (array[i]<= '9')) { //짝수번째 숫자 *로 치환
array[i] = '*';
}
System.out.print(array[i]);
}
System.out.println();
}
}
import re
def main(inp) :
inp_ev = inp[1::2]
EOD_com = re.compile("\d")
inp_ev = EOD_com.sub('*', inp_ev)
for i in range(0, len(inp_ev)) :
inp = inp.replace(inp[2*i+1], inp_ev[i])
return inp
if __name__ == '__main__' :
print(main(input("INPUT : ")))
먼저 입력된 문자열의 짝수번째만 따로 모은 뒤, 정규식으로 숫자만 *로 바꿔서 다시 문자열에 돌려놓았습니다.
결과
INPUT : a1b2cde3~g45hi6
a*b*cde*~g4*hi6
N = list(input("Example: "))
for i in range(1,len(N)):
if i % 2 != 0:
try:
int(N[i])
N[i] = '*'
except ValueError:
pass
finish = ""
for i in range(len(N)):
finish += N[i]
print("→ ",finish)
def subs(n):
val=''
ln=[]
nd=[]
nl=[]
for i in range(len(n)):
ln.append(n[i])
for i in range(int(len(n)/2)):
try:
nd.append(n[i*2+1])
nd[i]=int(nd[i])
nl.append(i*2+1)
except:
pass
for i in range(len(nl)):
del ln[int(nl[i])]
ln.insert(nl[i],'*')
for i in range(len(ln)):
val+=ln[i]
print(val)
subs(input())
def subs():
input_string = input("문자열: ")
input_list = list(input_string)
for i in range(0, len(input_list)):
if i % 2 == 1:
input_list[i] = "*"
i += 1
result = "".join(input_list)
return result
python 3.8
a='a1b2cde3~g45hi6'
for i in range(len(a)) :
print("*" if (a[i]).isnumeric() and i&1 else a[i],end='')
# 3항 연산자를 이용, i&1은 홀수와 짝수를 결정 isdigit()도 동일한 결과 출력
end=''는 가로 방향 연속 출력을 위해 입력됨.
이 문제에 대한 상파님의 아이디어를 활용하여 윗식을 아래식으로 교체해보았습니다.
for i in range(len(a)):
print([a[i],'*'][i&1 and a[i].isdigit()],end='')
#include <iostream>
#include <string>
using namespace std;
/*
모든 짝수번째 숫자를 * 로 치환하시오.
(홀수번째 숫자,또는 짝수번째 문자를 치환하면 안됩니다.) 로직을 이용하면 쉬운데 정규식으로는 어려울거 같아요.
Example: a1b2cde3~g45hi6 → a*b*cde*~g4*hi6
*/
void Func(string s) {
cout << s << " -> ";
int n;
for (int i = 0; i < s.length(); i++) {
if ((i + 1) % 2 == 0) {
n = s[i] - '0';
for (int j = 0; j <= 9; j++) {
if (n == j) { s[i] = '*'; }
}
}
}
cout << s << endl;
}
int main() {
Func("a1b2cde3~g45hi6");
}
a = list(input("입력: "))
for i in range(1, len(a), 2):
if a[i].isdigit()== True:
a[i] = "*"
print("".join(a))
s = 'a1b2cde3~g45hi6'
print(''.join(['*' if (i % 2 == 1) and (s[i].isdigit()) else s[i] for i in range(len(s))]))
cur=list(input("Example: "))
for i in range(len(cur)):
if (i+1)%2==0 and cur[i]>='1' and cur[i]<'9':
cur[i]="*"
Str=""
for i in range(len(cur)):
Str+=cur[i]
print(Str)
st=input('문자숫자 섞어서 .... : ')
for i in range(len(st)):
try:
if int(st[i])%2==0:
if i%2==0:
st=st.replace(st[i],'*')
else:pass
else:
pass
except:
pass
print(st)
def convert_even_digit(s):
convert = lambda i: "*" if i % 2 != 0 and s[i].isdigit() else s[i]
return "".join([convert(i) for i in range(len(s))])
Example = list(input())
for i in range(1, len(Example), 2):
if Example[i].isdigit():
Example[i] = '*'
print(Example)
a=list(input())
b=[]
for i in range(0,len(a)):
try:
if i%2==0:
b.append(a[i])
elif i%2!=0 and int(a[i]):
b.append('*')
except:
b.append(a[i])
print(''.join(b))
파이썬3입니다.
a = list(input('type any words.'))
b = ['*' if a.index(x) % 2 == 1 and x.isdigit() else x for x in a]
print(''.join(b))
char인 숫자를 int로 변환하면 어떻게 되는지 배웠다!
import java.util.ArrayList;
import java.util.Scanner;
//모든 짝수번째 숫자를 * 로 치환하시오.(홀수번째 숫자,또는 짝수번째 문자를 치환하면 안됩니다.)
//Example: a1b2cde3~g45hi6 → a*b*cde*~g4*hi6
//아스키 코드에 대해 배움 1~9 → 49~57
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String a = scan.nextLine();
char[] list = a.toCharArray();
for(int i=0;i<list.length;i++)
{
if(i%2==1)
{
if((int)list[i]>48 && (int)list[i]<58)
System.out.print("*");
else
System.out.print(list[i]);
}
else
System.out.print(list[i]);
}
}
}
a = input("Enter: ")
def Digit_word(word):
W=[x for x in word]
p=""
for i in range(len(W)):
if i%2!=0:
if W[i].isnumeric():
W[i]="*"
p+=W[i]
print(p)
Digit_word(a)
package test;
public class Test{
public static void main(String args[]) {
String a = "a1b2cde3~g45hi6";
for(int i=0; i< a.length(); i++) {
if(a.indexOf(a.charAt(i)) % 2 == 1 && Character.getNumericValue(a.charAt(i)) < 10) {
System.out.print('*');
}
else{System.out.print(a.charAt(i));}
}
}
}
public class test13 {
public static void main(String[] args) {
String input = "a1b2cde3~g45hi6";
StringBuffer buffer = new StringBuffer(input);
for(int i = 0; i < buffer.length(); i++) {
if(i % 2 == 1) {
buffer.setCharAt(i,isParsable(buffer.charAt(i)));
}
}
System.out.println(buffer);
}
public static char isParsable(char input) {
try {
Integer.parseInt(String.valueOf(input));
return '*';
} catch (final NumberFormatException e) {
return input;
}
}
}
s = "a1b2cde3~g45hi6"
result = ""
for i in range(0, len(s)):
if i % 2 == 1 and s[i].isdigit():
result += "*"
else:
result += s[i]
print(result)
#55 Level 2 : https://codingdojang.com/scode/428
def digit(text):
temp = list(text)
# result = []
for i in range(1, len(temp), 2):
if temp[i].isdigit():
temp[i] = '*'
return ''.join(temp)
print(digit('a1b2cde3~g45hi6'))
package main;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//문자열로 문자를 입력하고
//배열로 하나씩 저장하고 배열은 홀수 번째에 있는 값을 *로 변환 하고
//배열을 출력
String str = "";
str = sc.next();
char[] arStr = new char[str.length()];
for (int i = 0; i < arStr.length; i++) {
if(i%2==1) {
arStr[i] = '*';
}else {
arStr[i] = str.charAt(i);
}
}
for (int i = 0; i < arStr.length; i++) {
System.out.print(arStr[i]);
}
}
}
def Every_Other_Digit(strings):
numbers=['1','2','3','4','5','6','7','8','9','0']
for_answer=[]
for i in range(0,len(strings),1):
if (i+1)%2==0 and strings[i] in numbers:
for_answer.append("*")
else:
for_answer.append(strings[i])
print("".join(for_answer))
Every_Other_Digit("a1v2cde3~g45hi6")
text = list('a1b2cde3~g45hi6')
''.join(['*' if text[x].isdigit() and x%2==1 else text[x] for x in range(len(text))])
s = list(input("Example: "))
for i,c in enumerate(s):
if((i+1) % 2 == 0):
if(47<ord(c)<58):
s[i] = '*'
print("".join(s))
EOD = 'a1b2cde3~g45hi6'
l = list(EOD)
for index in range(1, len(EOD),2):
if EOD[index].isdigit():
l[index]='*'
print(''.join(l))
import java.util.Scanner;
public class EveryOtherDigit {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String example = s.nextLine();
StringBuilder sb = new StringBuilder(example);
for (int i = 0; i < sb.length(); i++) {
if ((i + 1) % 2 == 0 && Character.isDigit(sb.charAt(i))) {
sb.setCharAt(i, '*');
}
}
System.out.println(sb);
}
}
line = 'a1b2cde3~g45hi6'
line_list = list(line)
for i, v in enumerate(line_list):
if i % 2 != 0 and v.isdecimal() == True:
line_list[i] = '*'
print(''.join(line_list))
a = input("data")
for i in range(len(a)):
if i%2==1 and a[i].isdigit():
print("*",end="")
else:
print(a[i],end= "")
const ary=prompt('문자열을 입력','').split('');
const number=/[0-9]/;
const result=ary.map((el,index)=>{
(index%2==1 && number.test(el))?el='*':el=el;
return el;
})
console.log(result.join(''))
파이썬입니다
str1=input()
str2=str1[0]
for i in range(1,len(str1)):
if i%2!=0:
if 48<=ord(str1[i])<=57: # if str1[i].isdigit():
str2=str2+"*"
else:
str2=str2+str1[i]
else:
str2=str2+str1[i]
print(str)
code = "a1b2cde3~g45hi6"
replaced_code = ""
for n in range(len(code)):
if n%2 == 0:
replaced_code += code[n]
elif n%2 == 1:
if code[n].isdigit() == True:
replaced_code += "*"
else :
replaced_code += code[n]
print(replaced_code)
def convert(s):
output = ''
for i in range(0, len(s)):
if i % 2 != 0 and s[i].isdigit() is True:
output += "*"
else:
output += s[i]
return output
print(convert('a1b2cde3~g45hi6'))
def makeAns(str_):
str2_=""
for i in range(0, len(str_)):
if i % 2 == 1 and str_[i].isdigit():
str2_ = str2_ + "*"
else:
str2_ = str2_ + str_[i]
print(str2_)
makeAns("a1b2cde3~g45hi6")
결과
a*b*cde*~g4*hi6
def findEvenNum(a):
temp=[]
for i in range(len(list(a))):
if i%2 !=0 and a[i].isnumeric():
temp.append("*")
else:
temp.append(a[i])
return "".join(temp)
g = [1,2,3,4,5,6,7,8,9,0]
h = "a1b2cde3~g45hi6"
def share(n):
e = []
for a in n:
e.append(a)
return e
def in(z):
for b in z:
if z.index(b)/2 in g and b in g:
z[z.index] = "*"
return z
def hab(e):
t = ""
for mk in e:
t = str(t) + str(mk)
return t
r = share(h)
r = in(r)
print(had(r))
e = 'a1b2cde3~g45hi6'
q = []
for i in e :
if 47<ord(i)<58 : q.append('*')
else : q.append(i)
E = ''.join(q)
print(E)
#codingdojing_everyOtherDgit
a = 'a1b2cde3~g45hi6' #immutable
_a = list(a) #mutable
for i in range(1,len(a),2):
if _a[i].isdigit(): _a[i] = '*'
print(''.join(_a))
파이썬 3.8.10으로 작성했습니다.
sample = 'a1b2cde3~g45hi6'
def star_likes_two(st):
new_st = ''
index = 0
for s in st:
index += 1
if index % 2 == 0 and s.isdigit():
new_st += '*'
else:
new_st += s
return new_st
print(star_likes_two(sample))
n = input("")
s = ""
nlist = [x for x in n ]
for i in nlist :
if nlist.index(i) % 2 != 0 and i.isdigit() == True: s += "*"
else : s += i
print(s)
data = 'a1b2cde3~g4hi6'
sun =0
for i in data:
sun += 1
if sun % 2 == 0 and i in "0123456789":
data=data.replace(i,'*')
print(data)
S = input("문자열을 입력하세요 : ") n = len(S) S = list(S)
for i in range(n): if i % 2 == 1 and ord(S[i]) >= 48: if ord(S[i]) <= 57: S[i] = "*" S = ''.join(S) print(S)
lst=list(input())
for i in range(len(lst)):
if i%2 ==1 and lst[i].isdigit():
lst[i]='*'
print(''.join(lst))
def change_even_digit(s):
for i in range(len(s)):
if i%2 == 1 and s[i].isdigit():
print('*',end='')
else:
print(s[i],end='')
print("")
if __name__ == '__main__':
s = 'a1b2cde3~g45hi6'
change_even_digit(s)
public class Every_Other_Digit {
public static void main(String[] args) {
System.out.print("문자를 입력하세요: ");
Scanner sc = new Scanner(System.in);
String st = sc.nextLine();
for(int i =0 ; i<st.length(); i++) {
if((i+1)%2==0 &&
st.charAt(i)<'9' && st.charAt(i)>'0'){
System.out.print('*');
}
else {
System.out.print(st.charAt(i));
}
}
}
}
자바스크립트로 풀었습니다.
function tranceform(str) {
for(var i in str)
if(i%2 != 0 && isNaN(Number(str[i])) != true) str = str.replace(str[i], '*')
return str
}
tranceform("a1b2cde3~g45hi6")
string = input(":")
count = 1
af_string =[]
for i in string:
if count % 2 == 0:
if i.isdigit():
i = "*"
af_string.append(i)
else:
af_string.append(i)
count += 1
print("".join(af_string))
sentence = list(input("아무 문장을 입력하세요"))
for i in range(1,len(sentence),2) :
if ord(sentence[i]) >=48 and ord(sentence[i]) <= 57 :
sentence.pop(i)
sentence.insert(i,"*")
a = "".join(sentence)
print(a)
str = "a3b1cde6~g45hi6"
s = list(str)
for i in range(len(s)):
if (i%2==1) and (s[i].isdigit()):
s[i]="*"
s = "".join(s)
if s=="a*b*cde*~g4*hi6":
print("정답입니다.")
_input = input("Example : ")
print( "".join( list( map( lambda x : x[1] if x[0]%2 == 0 or x[1] not in "0123456789" else "*",enumerate(_input) ) ) ) )
a = 'a1b2cde3~g45hi6'
b = [x for x in a]
for i in range(1, len(a),2):
if ord('0')<= ord(a[i]) <= ord('9'):
b[i] = '*'
print(''.join(b))
def evennum_change(data):
data = list(data)
for i, word in enumerate(data):
if i % 2 != 0 and word.isdigit():
data[i] = "*"
return "".join(data)
a = "a1b2cde3~g45hi612"
print(evennum_change(a))
quiz = "a1b2cde3~g45hi6"
# 문자열 순서 변수 생성
count = 1
# 짝수번째이면서 숫자면 *, 아니면 문자열 출력
for i in quiz:
if count % 2 == 0 and i.isdigit():
print("*", end="")
else:
print(i, end="")
count += 1
# 답 = a*b*cde*~g4*hi6
하나의 자리수에 들어올 수 있는 짝수는 2,4,6,8 뿐이라서 요렇게 얌체같이 짜봣슴돠...
public class EvenNum {
public static void main(String[] args) {
String str = "a1b2cde3~g45hi6";
char[] ch = str.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (ch[i] == '2' || ch[i] == '4' || ch[i] == '6' || ch[i] == '8') {
ch[i] = '*';
}
}
String result = new String(ch);
System.out.println(result);
}
}
a='a1b2cde3~g45hi6'
for i in a:
if a.index(i)%2==1:
if 48<=ord(i) and ord(i)<=57:
i='*'
print(i,end="")
import re
def EveryOtherDigit():
string = input()
for i in range(len(string)):
if i % 2 == 1:
if re.search('\d', string[i]):
string = string.replace(string[i], '*')
return print(string)
EveryOtherDigit() # a1b2cde3~g45hi6
example = 'a1b2cde3~g45hi6'
count = 0
result = ''
for i in example:
count += 1
if count % 2 == 0:
if i in '0123456789':
result += '*'
else: result += i
else: result += i
print(result)
cmd = input("변환할 문장을 입력하시오 :")
cmd_list = []
num = 0
for i in range(0, len(cmd)): #입력받은 문장을 리스트로 변환
cmd_list.append(cmd[i])
for n in range(0, len(cmd_list)): #짝수번째에 있는 글자를 *로 치환
if n % 2 == 1:
num = n
cmd_list[num] = '*'
cmd_char = ''.join(l for l in cmd_list) #리스트를 문자열로 변환
print(cmd_char)
파이썬 3.11버전입니다.
문자열 변경에서 a.replace 하면 a의 문자열이 바뀌는 줄 알았는데 a = a.replace 해야하네요
a = input()
for i in range(0,len(a)):
b = a[i].isdigit()
if i % 2 == 1 :
if a[i].isdigit() == True:
a = a.replace(a[i],"*")
print(a)
a = list(input())
for i in range(len(a)):
if i %2 ==1 and a[i].isdecimal():
a[i] = '*'
print("".join(a))
Python.
origin_sentence = 'a1b2cde3~g45hi6'
def digit_to_star(sentence):
edited_sentence = '' #결괏값을 넣어 줄 문자열 변수 생성
for i in sentence:
if i in "1234567890": #문자열 내의 문자 i가 숫자일 경우
if (sentence.index(i)+1) % 2 == 0: #index에 1을 더한 수(index는 0부터 시작하므로)가 짝수일 경우(즉, 해당 문자가 짝수 번째 숫자일 경우)
i = '*' #해당 문자를 *로 치환
edited_sentence += i #결괏값을 넣을 문자열에 추가
elif (sentence.index(i)+1) % 2 == 1: #해당 문자가 홀수 번째 숫자일 경우
edited_sentence += i #결괏값을 넣을 문자열에 그대로 추가
else: #문자열 내의 문자 i가 숫자가 아닐 경우
edited_sentence += i #그대로 결괏값에 추가
return edited_sentence #최종 결괏값 출력
print(digit_to_star(origin_sentence))
a = input("input your sentence: ")
b = len(a)
result = list(a)
for i in range(b-1):
if i%2 == 0:
for x in a[i+1]:
if x.isdigit() == True:
result[i+1] = '*'
result_str = ''.join(result)
print(result_str)
value=list(input())
result=""
for i in range(len(value)):
if i%2==1 and value[i].isdigit():
result+="*"
else:
result+=value[i]
print(result)
x = "a1b2cde3~g45hi6" # 예시
x = list(x) # 리스트 변환
for i in range(1, len(x), 2): # 짝수번째만 받아오도록 순환
if x[i].isdigit(): # 숫자인지 확인하는 함수
x[i] = "*" # True일 경우 *로 치환
print(''.join(x)) #문자열로 재변환해서 출력
def eod():
s = "a1b2cde3~g45hi6"
for e in s[1::2]:
if e.isnumeric() == True:
s = s.replace(e, '*')
print(s)
eod()
JAVA입니다.
package question4.every_other_digit;
public class Main {
public static void main(String[] args) {
String input = "a1b2cde3~g45hi6";
char[] inputChars = input.toCharArray();
String output = "";
for (int i = 0; i < inputChars.length; i++) {
String c = Character.toString(inputChars[i]);
if(i%2 == 1) {
try {
Integer.parseInt(c);
c = "*";
} catch (Exception e) {
}
}
output = output + c;
}
System.out.println(output);
}
}