Skip to content

Instantly share code, notes, and snippets.

@AlicanAkkus
Last active August 8, 2016 07:55
Show Gist options
  • Save AlicanAkkus/1df42151ad034635767baf41930cdee0 to your computer and use it in GitHub Desktop.
Save AlicanAkkus/1df42151ad034635767baf41930cdee0 to your computer and use it in GitHub Desktop.
Basit bir string formatlama işlemi.
package com.wora.formatter;
public class StringFormatter {
public static synchronized String format(String text, Object... parameters) {
try {
int beginIndex = 0;
String delimeter = "{" + beginIndex + "}";
//params yok veya null ise gelen text'i geri gönder.
if (parameters != null && parameters.length > 0) {
//en az bir tane format karekter icerdiginden emin ol.
if(text.indexOf(delimeter) > -1){
//tüm {XXX} formatlarını bulup replace et.
while (text.indexOf(delimeter) > -1) {
String formatParam = (String) parameters[beginIndex];
text = text.replace(delimeter, formatParam);
beginIndex++;
delimeter = "{" + beginIndex + "}";
}
}else{
throw new RuntimeException("No matched any format in text!");
}
}else{
return text;
}
} catch (Exception e) {
// logger.error(e, e);
e.printStackTrace();
}
return text;
}
public static void main(String[] args) {
String text = "Hello, {0}. How {1} are you?";
System.out.println(StringFormatter.format(text, "Alican", "old"));//Hello, Alican. How old are you?
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment