Skip to content

Commit

Permalink
Fix string formatting for localized strings in material3 to correctly…
Browse files Browse the repository at this point in the history
… handle %N$d and %N$s strings.
  • Loading branch information
m-sasha committed Mar 4, 2024
1 parent cbb519d commit 3156c0d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,9 @@ internal actual value class Strings(val value: Int) {
internal actual fun String.format(vararg formatArgs: Any?): String {
var result = this
formatArgs.forEachIndexed { index, arg ->
result = result.replace("%${index+1}$", arg.toString())
result = result
.replace("%${index+1}\$d", arg.toString())
.replace("%${index+1}\$s", arg.toString())
}
return result
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,28 +28,46 @@ class StringFormatTest {
}

@Test
fun one_arg() {
val result = "str %1\$".format(1)
fun one_number_arg() {
val result = "str %1\$d".format(1)
assertEquals("str 1", result)
}

@Test
fun two_args() {
val result = "str %1\$ %2\$".format(1, 2)
fun one_string_arg() {
val result = "str %1\$s".format("1")
assertEquals("str 1", result)
}

@Test
fun two_number_args() {
val result = "str %1\$d %2\$d".format(1, 2)
assertEquals("str 1 2", result)
}

@Test
fun two_string_args() {
val result = "str %1\$s %2\$s".format("1", "2")
assertEquals("str 1 2", result)
}

@Test
fun string_and_number_args() {
val result = "str %1\$s %2\$d".format("1", 2)
assertEquals("str 1 2", result)
}

@Test
fun too_many_args() {
val result = "str %1\$".format(1, 2)
val result = "str %1\$d".format(1, 2)
assertEquals("str 1", result)
}

@Test
fun not_enough_args() {
// Behavior is not specified. We can consider different variants.
val result = "str %1\$".format()
assertEquals("str %1\$", result)
val result = "str %1\$d".format()
assertEquals("str %1\$d", result)
}

}

0 comments on commit 3156c0d

Please sign in to comment.