Program Tip

.NET의 String.Format에 해당하는 Java

programtip 2020. 12. 2. 21:48
반응형

.NET의 String.Format에 해당하는 Java


String.FormatJava 에 .NET에 해당하는 것이 있습니까?


String.formatPrintStream.format 메서드를 살펴보십시오 .

둘 다 java.util.Formatter 클래스를 기반으로합니다 .

String.format 예 :

Calendar c = new GregorianCalendar(1995, MAY, 23);
String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c);
// -> s == "Duke's Birthday: May 23, 1995"

System.out.format 예 :

// Writes a formatted string to System.out.
System.out.format("Local time: %tT", Calendar.getInstance());
// -> "Local time: 13:34:18"

이에 대한 10 센트 대답은 다음과 같습니다.

C #


String.Format("{0} -- {1} -- {2}", ob1, ob2, ob3)

Java의


String.format("%1$s -- %2$s -- %3$s", ob1, ob2, ob3)

1부터 시작하는 인덱스에 유의하십시오. "s"는 .toString ()을 사용하여 문자열로 변환하는 것을 의미합니다. 사용 가능한 다른 많은 변환 및 서식 옵션이 있습니다.

http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax


MessageFormat.format().net 표기법을 사용하는 것이 있습니다 .


%s인덱스가 옵션 인수이기 때문에 단순히 문자열에 사용할 수도 있습니다 .

String name = "Jon";
int age = 26;
String.format("%s is %s years old.", name, age);

덜 시끄 럽습니다.

%sJava 문서 에 대한 참고 사항 :

인수 arg가 널이면 결과는 "null"입니다. arg가 Formattable을 구현하면 arg.formatTo가 호출됩니다. 그렇지 않으면 arg.toString ()을 호출하여 결과를 얻습니다.


String.format구문은 .NET과 약간 다르지만 Java 에는 있습니다 .


이것은 실제로 OP의 질문에 대한 대답은 아니지만 C # 스타일의 "형식 항목"을 포함하는 문자열로 문자열을 대체하는 간단한 방법을 찾는 다른 사람들에게 도움이 될 수 있습니다.

   /**
    * Method to "format" an array of objects as a single string, performing two possible kinds of
    * formatting:
    *
    * 1. If the first object in the array is a String, and depending on the number of objects in the
    *    array, then a very simplified and simple-minded C#-style formatting is done. Format items
    *    "{0}", "{1}", etc., are replaced by the corresponding following object, converted to string
    *    (of course). These format items must be as shown, with no fancy formatting tags, and only
    *    simple string substitution is done.
    *
    * 2. For the objects in the array that do not get processed by point 1 (perhaps all of them,
    *    perhaps none) they are converted to String and concatenated together with " - " in between.
    *
    * @param objectsToFormat  Number of objects in the array to process/format.
    * @param arrayOfObjects  Objects to be formatted, or at least the first objectsToFormat of them.
    * @return  Formatted string, as described above.
    */
   public static String formatArrayOfObjects(int objectsToFormat, Object... arrayOfObjects) {

      // Make a preliminary pass to avoid problems with nulls
      for (int i = 0; i < objectsToFormat; i++) {
         if (arrayOfObjects[i] == null) {
            arrayOfObjects[i] = "null";
         }
      }

      // If only one object, just return it as a string
      if (objectsToFormat == 1) {
         return arrayOfObjects[0].toString();
      }

      int nextObject = 0;
      StringBuilder stringBuilder = new StringBuilder();

      // If first object is a string it is necessary to (maybe) perform C#-style formatting
      if (arrayOfObjects[0] instanceof String) {
         String s = (String) arrayOfObjects[0];

         while (nextObject < objectsToFormat) {

            String formatItem = "{" + nextObject + "}";
            nextObject++;
            if (!s.contains(formatItem)) {
               break;
            }

            s = s.replace(formatItem, arrayOfObjects[nextObject].toString());
         }

         stringBuilder.append(s);
      }

      // Remaining objects (maybe all of them, maybe none) are concatenated together with " - "
      for (; nextObject < objectsToFormat; nextObject++) {
         if (nextObject > 0) {
            stringBuilder.append(" - ");
         }
         stringBuilder.append(arrayOfObjects[nextObject].toString());
      }

      return stringBuilder.toString();
   }

(그리고 궁금한 점이있는 경우 단일 로그 메시지에 여러 항목을 더 쉽게 기록 할 수 있도록 Android Log 메서드에 대한 간단한 래퍼의 일부로이 코드를 사용하고 있습니다.)

참고 URL : https://stackoverflow.com/questions/3754597/java-equivalent-to-nets-string-format

반응형