Jak korzystać z Javy.Sznurek.format w Scali?

Próbuję użyć metody .format ciągu znaków. Ale jeśli umieszczę %1, %2 itd. w ciąg, java.util.UnknownFormatConversionException jest rzucany, wskazując na mylący fragment kodu źródłowego Javy:

private void checkText(String s) {

    int idx;

    // If there are any '%' in the given string, we got a bad format
    // specifier.
    if ((idx = s.indexOf('%')) != -1) {
        char c = (idx > s.length() - 2 ? '%' : s.charAt(idx + 1));
        throw new UnknownFormatConversionException(String.valueOf(c));
    }
}

Z tego rozumiem, że % char jest zabroniony. Jeśli tak, to czego powinienem użyć do zastępczych argumentów?

Używam Scala 2.8.

Author: Daniel Kaplan, 2010-09-12

11 answers

Podczas gdy wszystkie poprzednie odpowiedzi są poprawne, wszystkie są w Javie. Oto przykład Scali:

val placeholder = "Hello %s, isn't %s cool?"
val formatted = placeholder.format("Ivan", "Scala")

Mam również wpis na blogu o robieniu format Jak w Pythonie% operator , który może być przydatny.

 298
Author: pr1001,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-07 19:05:22

Nie musisz używać liczb do wskazywania pozycji. Domyślnie pozycja argumentu jest po prostu kolejnością, w jakiej pojawia się on w łańcuchu.

Oto przykład właściwego sposobu użycia:

String result = String.format("The format method is %s!", "great");
// result now equals  "The format method is great!".

Zawsze będziesz używać %, po którym następuje kilka innych znaków, aby poinformować metodę, jak powinna wyświetlać łańcuch znaków. %s jest prawdopodobnie najbardziej rozpowszechniony i oznacza to tylko, że argument powinien być traktowany jako ciąg znaków.

Nie wymienię wszystkich opcji, ale podam kilka przykładów, aby dać ci pomysł:

// we can specify the # of decimals we want to show for a floating point:
String result = String.format("10 / 3 = %.2f", 10.0 / 3.0);
// result now equals  "10 / 3 = 3.33"

// we can add commas to long numbers:
result = String.format("Today we processed %,d transactions.", 1000000);
// result now equals  "Today we processed 1,000,000 transactions."

String.format po prostu używa java.util.Formatter, więc pełny opis opcji można zobaczyć Formatter javadocs.

I, jak wspomina BalusC, zobaczysz w dokumentacji, że można zmienić domyślną kolejność argumentów, jeśli zajdzie taka potrzeba. Jednak prawdopodobnie jedynym czasem, w którym musisz / chcesz to zrobić, jest użycie tego samego argumentu więcej niż raz.

 298
Author: TM.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-02 16:35:09

Zamiast patrzeć na kod źródłowy, powinieneś przeczytać javadoc String.format () i składnia Formatera .

Określa się format wartości po%. Na przykład dla liczby dziesiętnej jest to d, A Dla ciągu jest to s:

String aString = "world";
int aInt = 20;
String.format("Hello, %s on line %d",  aString, aInt );

Wyjście:

Hello, world on line 20

Aby zrobić to, co próbowałeś (użyj indeksu argumentów), używasz: *n*$,

String.format("Line:%2$d. Value:%1$s. Result: Hello %1$s at line %2$d", aString, aInt );

Wyjście:

Line:20. Value:world. Result: Hello world at line 20
 127
Author: OscarRyz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-30 17:43:47

Możesz użyć tego;

String.format("%1$s %2$s %2$s %3$s", "a", "b", "c");

Wyjście:

A b B c

 70
Author: Engin Ardıç,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-06 07:13:33

Zauważ również, że Scala rozszerza łańcuch za pomocą wielu metod (poprzez konwersję do WrappedString wprowadzonego przez Predef), więc możesz również wykonać następujące czynności:

val formattedString = "Hello %s, isn't %s cool?".format("Ivan", "Scala")
 13
Author: denis phillips,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-09-12 23:37:41

Oficjalnym odniesieniem jest klasa Formatter.

 11
Author: Alberto Segura,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-23 19:46:52

In Scala 2.10

val name = "Ivan"
val weather = "sunny"

s"Hello $name, it's $weather today!"
 8
Author: Londo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-05 22:14:21

To jest lista tego, co String.format może zrobić. To samo dotyczy printf

int i = 123;
o.printf( "|%d|%d|%n" ,       i, -i );      // |123|-123|
o.printf( "|%5d|%5d|%n" ,     i, -i );      // |  123| –123|
o.printf( "|%-5d|%-5d|%n" ,   i, -i );      // |123  |-123 |
o.printf( "|%+-5d|%+-5d|%n" , i, -i );      // |+123 |-123 |
o.printf( "|%05d|%05d|%n%n",  i, -i );      // |00123|-0123|

o.printf( "|%X|%x|%n", 0xabc, 0xabc );      // |ABC|abc|
o.printf( "|%04x|%#x|%n%n", 0xabc, 0xabc ); // |0abc|0xabc|

double d = 12345.678;
o.printf( "|%f|%f|%n" ,         d, -d );    // |12345,678000|     |-12345,678000|
o.printf( "|%+f|%+f|%n" ,       d, -d );    // |+12345,678000| |-12345,678000|
o.printf( "|% f|% f|%n" ,       d, -d );    // | 12345,678000| |-12345,678000|
o.printf( "|%.2f|%.2f|%n" ,     d, -d );    // |12345,68| |-12345,68|
o.printf( "|%,.2f|%,.2f|%n" ,   d, -d );    // |12.345,68| |-12.345,68|
o.printf( "|%.2f|%(.2f|%n",     d, -d );    // |12345,68| |(12345,68)|
o.printf( "|%10.2f|%10.2f|%n" , d, -d );    // |  12345,68| | –12345,68|
o.printf( "|%010.2f|%010.2f|%n",d, -d );    // |0012345,68| |-012345,68|

String s = "Monsterbacke";
o.printf( "%n|%s|%n", s );                  // |Monsterbacke|
o.printf( "|%S|%n", s );                    // |MONSTERBACKE|
o.printf( "|%20s|%n", s );                  // |        Monsterbacke|
o.printf( "|%-20s|%n", s );                 // |Monsterbacke        |
o.printf( "|%7s|%n", s );                   // |Monsterbacke|
o.printf( "|%.7s|%n", s );                  // |Monster|
o.printf( "|%20.7s|%n", s );                // |             Monster|

Date t = new Date();
o.printf( "%tT%n", t );                     // 11:01:39
o.printf( "%tD%n", t );                     // 04/18/08
o.printf( "%1$te. %1$tb%n", t );            // 18. Apr
 3
Author: PRO_gramista,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-23 11:12:54

Oto lista formaterów używanych z String.format ()

Http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html

 2
Author: NixRam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-28 11:31:20

Chociaż @ Londo wspomniał o interpolatorze Scali"s" string, myślę, że interpolator Scali " f " string string jest bardziej odpowiedni do pierwotnego pytania. Przykład użyty kilka razy w innych odpowiedziach można również napisać (od Scali 2.10) w ten sposób:

scala> val name = "Ivan"
name: String = Ivan
scala> val thing = "Scala"
thing: String = Scala
scala> val formatted = f"Hello $name%s, isn't $thing%s cool?"
formatted: String = Hello Ivan, isn't Scala cool?

W związku z pytaniem pierwotnym należy pamiętać, że:

  • formatted jest zdefiniowany za pomocą łańcucha, który jest poprzedzony literą "f". Jest to interpolator Łańcuchowy" f " (formatujący).
  • "f" string interpolator uses java.util.Formatter
  • java.lang.String.format używa tego samego java.util.Formatter

Dobrą rzeczą w interpolacji łańcuchów jest to, że pozwala zobaczyć, która zmienna jest zastępowana bezpośrednio w łańcuchu, zamiast dopasowywać ją do argumentów metody String.format.

 1
Author: Reid Spencer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-09 20:42:35

W Scali, dla interpolacji łańcuchów mamy $ to ratuje dzień i ułatwia nam życie:

Na przykład: chcesz zdefiniować funkcję, która przyjmuje nazwę wejściową i wiek i mówi "Cześć" z nazwą i mówi jej wiek. Można to napisać tak:

def funcStringInterpolationDemo(name:String,age:Int)=s"Hey ! my name is $name and my age is $age"

Stąd, gdy wywołujesz tę funkcję: tak:

funcStringInterpolationDemo("Shivansh",22)

Jego wynik będzie:

Hey ! my name is Shivansh and my age is 22

Możesz napisać kod, aby go zmienić w tej samej linii, np. jeśli chcesz dodać 10 lat do wiek !

Wtedy funkcja może być :

def funcStringInterpolationDemo(name:String,age:Int)=s"Hey ! my name is $name and my age is ${age+10}"

A teraz wyjście będzie:

Hey ! my name is Shivansh and my age is 32
 0
Author: Shiv4nsh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-21 10:24:00