0

I have the following code, and i want to have a toast message that says "Congratulations nameToasted, you made 5 points!" but i get "CongratulationsnameToasted, you made5points!". i have already tried spacing on the strings.xml, but nothing.

String pointsInMessage = getString(R.string.congratulations) + nameToasted;
pointsInMessage = pointsInMessage + getString(R.string.you_made);
pointsInMessage = pointsInMessage + pointsPerAnswer;
pointsInMessage = pointsInMessage + getString(R.string.points_string) ;
  • You should add empty spaces, between concatenations. Even better, use a StringBuilder. As an alternative, you could join an array of strings using a space as the joining character. – Phantômaxx Aug 23 '17 at 16:44
  • just use `" "` [this is a space] while concatenations – Atef Hares Aug 23 '17 at 16:45
  • see https://stackoverflow.com/a/3753879/5515060 – Lino Aug 23 '17 at 16:57
  • See the Formatting Strings section of the [String Resources docs](https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling) – MidasLefko Aug 23 '17 at 20:09

3 Answers3

2

Try with String.format(), something like following:

final String pointsInMessage = String.format("%s %s, %s %d %s!", getString(R.string.congratulations), nameToasted, getString(R.string.you_made), pointsPerAnswer, getString(R.string.points_string));

Assuming that pointsPerAnswer is an Integer.

AlexTa
  • 5,133
  • 3
  • 29
  • 46
1

Do it like that:

String pointsInMessage = getString(R.string.congratulations) +" "+nameToasted;
Yoni
  • 1,346
  • 3
  • 16
  • 38
0

getString() always returns the string with .trim() applied so you can't use trailing and leading spaces in the strings.xml file.

Here is an example of a string builder you can use:

StringBuilder sb = new StringBuilder();
sb.append(R.string.congratulations).append(" ")
  .append(nameToasted).append(R.string.you_made).append(" ") 
  .append(pointsPerAnswer).append(" ").append(R.string.points_string);
String message = sb.toString();

this should give you the message you want to display.

theMTGDeckGenius
  • 167
  • 1
  • 12