I start learning Objective-C (after Java) and I encountered the following problem: I don’t know how to format a string, convert types and merge strings. In general, I want to display something like this (as if it looked in Java):

return "const value" + intVariable + stringVariable; 

    2 answers 2

    Using NSString:

     NSString *string1 = [NSString stringWithFormat:@"%@%d", @"constant string", 12345]; 

    Actually, the essence is the same as the usual sprintf. But there is a huge plus - the length will be calculated for you!

    Everything is there :).

      I have never met with objective-c in my life, but I assume that everything is the same as in ordinary C :).

      If you do not use any special class for strings, and only char * is bypassed, then something like this:

       char *result = new char[1024]; sprintf(result, "%s%d%s", "const value", intVariable, stringVariable); 

      Actually, what does this code do:

      First, we have a buffer in which we put the final line. The number 1024 is what I took from my head. The main thing is to have enough space. Most likely, it makes sense to calculate it as the length of your constant string plus strlen (stringVariable) plus a few characters so that the number exactly fits.

      Next, use the sprintf function (to get it, you need to enable stdio.h). It puts in its first argument a string corresponding to the format specified by the second argument, gathering it from all the others. This worst printf format is used in a lot of places, so it’s helpful to be familiar with it :)

      • The class for NSString strings is standard for obj-C. There seems to be a Util class of some kind ... - angry