2017-09-22 9 views
2

다른 문자열로 여러 문자열 자리 표시자를 채우고 싶은 코드로 작업하고 있습니다. 이것은 코드를 테스트하는 데 사용한 예제 텍스트입니다.Java : Map <String, String>을 사용하여 텍스트의 자리 표시자를 채우는 방법?

String myStr = "Media file %s of size %s has been approved" 

이것은 장소 소유자를 채우는 방법입니다. 몇 명의 장소 소유자를 사용할 것으로 예상되기 때문에 자바 맵 <>을 사용했습니다.

Map<String, String> propMap = new HashMap<String,String>(); 
propMap.put("file name","20mb"); 
String newNotification = createNotification(propMap); 

다음과 같은 방법으로 문자열을 생성했습니다.

public String createNotification(Map<String, String> properties){ 
    String message = ""; 
    message = String.format(myStr, properties); 

    return message; 
} 

두 개의 '% s'을 (를) "파일 이름"과 "20MB"로 바꾸려면 어떻게합니까?

답변

0

마침내 좋은 발견 해결책. 장소 소유자는이 [장소 소유자]와 같아야합니다.

2

String#format에 대한 귀하의 접근 방식이 잘못되었습니다.

가변적 인 양의 개체가지도가 아닌 두 번째 인수로 자리 표시자를 대체 할 것으로 예상합니다. 이들을 모두 그룹화하려면 배열이나 목록을 사용할 수 있습니다.

String format = "Media file %s of size %s has been approved"; 

Object[] args = {"file name", "20mb"}; 
String newNotification = String.format(format, args); 
3

지도가 의도 한 것이 아닙니다. 추가 할 항목은 "file name" -> "20 mb"이며 기본적으로 "파일 이름"속성의 값은 "20MB"입니다. 당신이 그것을하려고하는 것은 "아이템들의 튜플을 유지하는 것"입니다.

서식 지정 문자열의 고정 된 자리 표시 자 수 있음을 유의하십시오. 정확히 동일한 양의 항목을 포함하는 데이터 구조가 필요합니다. 기본적으로 배열 또는 List입니다.

Map<String,String> yourMap = //... 
for (Entry<String,String> e : yourMap) { 
    System.out.println(createNotification(e.getKey(), e.getValue())); 
} 
0

내가 %s 생각 :

따라서, 당신이 갖고 싶어하면 맵에있는 모든 항목의 알림을 만들려면, 당신은 같은 것을 할 필요가

public String createNotification(String[] properties) { 
    assert(properties.length == 2); // you might want to really check this, you will run into problems if it's false 
    return String.format("file %s has size %s", properties); 
} 

입니다 홀더를두기위한 파이썬의 문법입니다. 자바 환경에서는 이것을 사용할 수 없습니다. 그리고 당신의 방법 createNotification()은 두 개의 매개 변수를 필요로합니다.

+0

% s이 (가) 자바에서 사용할 수 _can_

public String createNotification(){ Pattern pattern = Pattern.compile("\\[(.+?)\\]"); Matcher matcher = pattern.matcher(textTemplate); HashMap<String,String> replacementValues = new HashMap<String,String>(); StringBuilder builder = new StringBuilder(); int i = 0; while (matcher.find()) { String replacement = replacementValues.get(matcher.group(1)); builder.append(textTemplate.substring(i, matcher.start())); if (replacement == null){ builder.append(matcher.group(0)); } else { builder.append(replacement); } i = matcher.end(); } builder.append(textTemplate.substring(i, textTemplate.length())); return builder.toString() } 
: 그러나 각각의 경우에 다른 수 https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax있다 –

1

당신은 단순히 VAR-args를 사용하여이 서식을 수행 할 수 있습니다

String myStr = "Media file %s of size %s has been approved"; 

    String newNotification = createNotification(myStr, "file name", "20mb"); 

    System.out.println(newNotification); 

패스 VAR-인수 createNotification 방법을, 여기에 코드입니다 : 여러 가지 방법을 시도 후

public static String createNotification(String myStr, String... strings){ 
    String message = ""; 
    message=String.format(myStr, strings[0], strings[1]); 

    return message; 
} 
+0

대체 할 문자열의 개수. 그러므로 나는 이것이 사용될 수 있다고 생각하지 않는다. – sndu

+0

@Sandu_prass 주어진 문자열 "% s의 미디어 파일 % s이 (가) 승인되었습니다"에 대한 것입니다. 우리는 약간의 변경을 통해 동적으로 만들 수 있습니다. –