419

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 ??

Rahul Sharma
  • 2,867
  • 2
  • 27
  • 40
Hubert
  • 16,012
  • 18
  • 45
  • 51
  • 2
    There are a few good answers, but none of them work for me (see my comments). The bounty is for any answer that provides a way to get a real space character (U+0020) as the first or last character of the string resource. – Thomas Oct 04 '10 at 09:14
  • 3
    Nasty nasty android :( – Allan Spreys Jun 17 '13 at 12:47

16 Answers16

570

Even if you use string formatting, sometimes you still need white spaces at the beginning or the end of your string. For these cases, neither escaping with \, nor xml:space attribute helps. You must use HTML entity &#160; for a whitespace.

Use &#160; for non-breakable whitespace.
Use &#032; for regular space.

Tot Zam
  • 8,406
  • 10
  • 51
  • 76
duessi
  • 6,050
  • 3
  • 18
  • 9
  • 12
    This *kind of* works, but it inserts a non-breaking space (U+00A0) instead of a regular space. That can be undesirable in some situations. – Thomas Oct 04 '10 at 09:10
  • For testing for instance, it's a total mess ! – Snicolas Jun 05 '12 at 07:10
  • 60
      doesn't work... xml editor gives an error and you can't to build the project... \u0020 works fine! – jcamacho Jul 29 '13 at 08:18
  • 13
    You need to add the semi colon (;) at the end. – user1010160 Sep 24 '15 at 07:19
  • 48
    \u0020 is generally the better solution. requires that you parse html and can be randomly ignored in some cases resulting in no space – HaydenKai Jul 21 '16 at 12:05
  • 10
    On Android Studio 3.2 deploying to an API 25 emulator, I used ` `, and I got no build error, but my space was still ignored. ` ` worked, but I don't want a non-breakable whitespace. I want just a regular space. `\u0020` worked. – Heath Borders Nov 27 '18 at 15:52
  • A good example for non-breaking space is `DateTimeFormatter.ofPattern("hh:mm\u00A0a")` – Sai May 22 '20 at 14:04
558

I ran into the same issue. I wanted to leave a blank at the end of a resource string representing an on-screen field name.

I found a solution on this issue report : https://github.com/iBotPeaches/Apktool/issues/124

This is the same idea that Duessi suggests. Insert \u0020 directly in the XML for a blank you would like to preserve.

Example :

<string name="your_id">Score :\u0020</string>

The replacement is done at build time, therefore it will not affect the performance of your game.

mostar
  • 4,723
  • 2
  • 28
  • 45
DavGin
  • 8,205
  • 2
  • 19
  • 26
  • works great. wonder what's the difference between using it and   – android developer Jul 18 '13 at 14:04
  • 3
    @androiddeveloper, \u indicates a unicode character as an escape sequence (not a unicode char directly in the file). nnn; indicates an html entity, which means that you're relying on your xml string being html parsed (it is by default when used in text views). See http://www.w3schools.com/html/html_entities.asp – greg7gkb Oct 31 '14 at 21:00
  • @greg7gkb Interesting, but I didn't know it's by default. You mean that if I use "setText" on the string resource, it will work the same? – android developer Oct 31 '14 at 22:05
  • @androiddeveloper Yes, I just confirmed this in code. You can have html entities in your strings xml file and they will be converted by default with setText(int resId). Example: T S T . – greg7gkb Oct 31 '14 at 23:01
  • 5
    `\u0020` is SPACE of ASCII code. This was the best choice for my project since I had to make sure it was ASCII. – OneWorld Nov 05 '14 at 09:42
162

This documentation suggests quoting will work:

<string name="my_str_spaces">" Before and after? "</string>
Rahul Sharma
  • 2,867
  • 2
  • 27
  • 40
Skywalker5446
  • 1,659
  • 1
  • 10
  • 5
  • 2
    Does it guarantee `" Before and after? "` – Prateek Jan 16 '13 at 12:44
  • 5
    Like this more than using unicode characters! Thanks! – anemo Jan 08 '15 at 10:19
  • 2
    Unfortunately some localization tools, like Passolo, automatically adds slash before quote. And string becomes this: \" Before and after? \". Therefore, this quotes appears in text. So using \u0020 seems to be better in this case. – Fox Jan 12 '16 at 08:58
  • I don't see this mentioned anywhere in the documentation. The closest I can see is `Enclose the entire string in double quotes ("This'll work", for example)` where it discusses escaping a `Single quote (')`. – Heath Borders Feb 26 '19 at 16:14
  • Relevant snippet from the docs: `By default Android will collapse sequences of whitespace characters into a single space. You can avoid this by enclosing the relevant part of your string in double quotes. In this case all whitespace characters (including new lines) will get preserved within the quoted region.` – Luke Needham Jan 18 '23 at 11:41
41

I just use the UTF code for space "\u0020" in the strings.xml file.

<string name="some_string">\u0020The name of my string.\u0020\u0020</string>

works great. (Android loves UTF codes)

Jasen
  • 471
  • 5
  • 5
30

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>
kyay10
  • 855
  • 8
  • 16
15

There is possible to space with different widths:

<string name="space_demo">|&#x20;|&#x2009;|&#x200A;||</string>

| SPACE | THIN SPACE | HAIR SPACE | no space |

Visualisation:

enter image description here

Andrew
  • 36,676
  • 11
  • 141
  • 113
12

use "" with the string resource value.

Example :

<string>"value with spaces"</string>

OR

use \u0020 code for spaces.

Harshad Pansuriya
  • 20,189
  • 8
  • 67
  • 95
Bhupendra Joshi
  • 233
  • 1
  • 5
  • 8
9

If you really want to do it the way you were doing then I think you have to tell it that the whitespace is relevant by escaping it:

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

However, I'd use string formatting for this. Something like the following:

<string name="Toast_Memory_GameWon">you found ALL PAIRS ! on %d flips !</string>

then

String message_all_pairs_found = String.format(getString(R.string.Toast_Memory_GameWon), total_flips);
Jeremy Logan
  • 47,151
  • 38
  • 123
  • 143
  • 1
    Escaping with a backslash does not work (for me at least). Using a format string is a great solution generally, but not always. For instance, `String.format` causes many memory allocations that are undesirable in a game. – Thomas Oct 04 '10 at 09:12
  • escaping the spaces (using the "\ " ) didn't work for me either. – android developer Jul 18 '13 at 13:52
  • 1
    Formatting only works if your text is all displayed in the same style. In my case the 2 things being joined are bold vs. normal and different colors. –  Dec 17 '14 at 16:11
8

Working well I'm using \u0020

<string name="hi"> Hi \u0020 </string>
<string name="ten"> \u0020 out of 10  </string>
<string name="youHaveScored">\u0020 you have Scored \u0020</string>

Java file

String finalScore = getString(R.string.hi) +name+ getString(R.string.youHaveScored)+score+ getString(R.string.ten);
               Toast.makeText(getApplicationContext(),finalScore,Toast.LENGTH_LONG).show();

Screenshot here Image of Showing Working of this code

Tarsbir Singh
  • 527
  • 5
  • 11
2

All answers here did not work for me. Instead, to add a space at the end of a string in XML i did this

<string name="more_store">more store<b> </b> </string>
Etienne Lawlor
  • 6,817
  • 18
  • 77
  • 89
2

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.

MPelletier
  • 16,256
  • 15
  • 86
  • 137
1

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>
Pavel Minaev
  • 99,783
  • 25
  • 219
  • 289
0

This may not actually answer the question (How to keep whitespaces in XML) but it may solve the underlying problem more gracefully.

Instead of relying only on the XML resources, concatenate using format strings. So first remove the whitespaces

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

And then build your string differently:

String message_all_pairs_found = 
      String.format(Locale.getDefault(), 
                    "%s %d %s", 
                    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();
Skusku
  • 558
  • 5
  • 11
0

There is also the solution of using CDATA. Example:

<string name="test"><![CDATA[Hello          world]]></string>

But in general I think \u0020 is good enough.

android developer
  • 114,585
  • 152
  • 739
  • 1,270
-2

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 for format the string (eg if you have an error returned by the server, otherwise use getString(R.string.string_resource_example)):

String message = context.getString(R.string.error_, "Server error message here")

Which results in:

Error: Server error message here
TheIT
  • 11,919
  • 4
  • 64
  • 56
-6

It does not work with xml:space="preserve"

so I did it the quickest way =>

I simply added a +" "+ where I needed it ...

String message_all_pairs_found = getString(R.string.Toast_Memory_GameWon_part1)+" "+total_flips+" "+getString(R.string.Toast_Memory_GameWon_part2);
Hubert
  • 16,012
  • 18
  • 45
  • 51