How to keep the spaces at the end and/or at the be

2019-01-04 16:10发布

I have to concatenate these two strings from my resource/value files:

<string name="Toast_Memory_GameWon_part1">you found ALL PAIRS ! on </string>
<string name="Toast_Memory_GameWon_part2"> flips !</string>

I do it this way :

String message_all_pairs_found = getString(R.string.Toast_Memory_GameWon_part1)+total_flips+getString(R.string.Toast_Memory_GameWon_part2);

Toast.makeText(this, message_all_pairs_found, 1000).show();

But the spaces at the end of the first string and at the beginning of the second string have disappeared (when the Toast is shown) ...

What should I do ?

I guess the answer is somewhere here in this documentation link

or is it something like using &amp ; for the "&" character ??

15条回答
等我变得足够好
2楼-- · 2019-01-04 16:34

If you need the space for the purpose of later concatenating it with other strings, then you can use the string formatting approach of adding arguments to your string definition:

<string name="error_">Error: %s</string>

Then format the string as:

String message = context.getString(R.string.error_, "Something went wrong")
查看更多
孤傲高冷的网名
3楼-- · 2019-01-04 16:35

I've no idea about Android in particular, but this looks like the usual XML whitespace handling - leading and trailing whitespace within an element is generally considered insignificant and removed. Try xml:space:

<string name="Toast_Memory_GameWon_part1" xml:space="preserve">you found ALL PAIRS ! on </string>
<string name="Toast_Memory_GameWon_part2" xml:space="preserve"> flips !</string>
查看更多
ゆ 、 Hurt°
4楼-- · 2019-01-04 16:36

This documentation suggests quoting will work:

<string name="my_str_spaces">" Before and after? "</string>
查看更多
Animai°情兽
5楼-- · 2019-01-04 16:36

use "" with the string resource value.

Example : "value with spaces"

OR

use \u0020 code for spaces.

查看更多
来,给爷笑一个
6楼-- · 2019-01-04 16:36

This question may be old, but as of now the easiest way to do it is to add quotation marks. For example:

<string name="Toast_Memory_GameWon_part1">"you found ALL PAIRS ! on "</string>
<string name="Toast_Memory_GameWon_part2">" flips !"</string>
查看更多
贼婆χ
7楼-- · 2019-01-04 16:36

An argument can be made for adding the space programmatically. Since these cases will be often used in concatenations, I decided to stop the madness and just do the old + " " +. These will make sense in most European languages, I would gather.

查看更多
登录 后发表回答