Can someone give a code example of how to right pad an NSString in objective-c please?
For example want these strings:
Testing 123 Long String
Hello World
Short
if right padded to a column width of say 12: and then a sting "XXX" is added to the end of each, it would give:
Testing 123 xxx
Hello World xxx
Short xxx
That is a 2nd column would like up.
Adam is on the right track, but not quite there. You do want to use +stringWithFormat:, but not quite as he suggested. If you want to pad "someString" to (say) a minimum of 12 characters, you'd use a width specifier as part of the format. Since you want the result to be left-justified, you need to precede the width specifier with a minus:
NSString *padded = [NSString stringWithFormat:#"%-12#", someString];
Or, if you wanted the result to be exactly 12 characters, you can use both minimum and maximum width specifiers:
NSString *padded = [NSString stringWithFormat:#"%-12.12#", someString];
2nd column of what would line up?
Given that you are on iOS, using HTML or a table view would be far more straightforward than trying to line up characters with spaces. Beyond being programmatically more elegant, it will look better, be more resilient to input data changes over time, and render a user experience more in line with expectations for the platform.
If you really want to use spaces, then you are going to have to limit your UI to a monospace font (ugly for readability purposes outside of specific contexts, like source code) and international characters are going to be a bit of a pain.
From there, it would be a matter of getting the string length (keeping in mind that "length" does not necessarily mean "# of characters" in some languages), doing a bit of math, using substringWithRange: and appending spaces to the result.
Unfortunately, Objective-C does not allow format specifiers for %#. A work-around for padding is the following:
NSString *padded = [NSString stringWithFormat:#"%#%*s", someString, 12-someString.length, ""];
which will pad the string to the right with spaces up to a field length of 12 characters.
%-# does not work, but %-s works
NSString *x = [NSString stringWithFormat:#"%-3#", #"a" ];
NSString *y = [NSString stringWithFormat:#"%-3#", #"abcd" ];
NSString *z = [NSString stringWithFormat:#"%-3# %#", #"a", #"bc" ];
NSString *zz = [NSString stringWithFormat:#"%-3s %#", "a", #"bc" ];
NSLog(#"[%#][%#][%#][%#].......", x,y,z,zz);
output:
[a][abcd][a bc][a bc].......
Try below. its working for me.
NSString *someString = #"1234";
NSString *padded = [someString stringByPaddingToLength: 16 withString: #"x" startingAtIndex:0];
NSLog(#"%#", someString);
NSLog(#"%#", padded);
First up, you're doing this a bad way. Please use separate labels for your two columns and then you will also be able to use proportional fonts. The way you're going about it you should be looking for an iPhone curses library.
If you really have to do it this way just use stringWithFormat:, like:
NSString *secondColumnString = #"xxx";
NSString *spacedOutString = [NSString stringWithFormat:#"testingColOne %#", secondColumnString];
NSString *spacedOutString = [NSString stringWithFormat:#"testingAgain %#", secondColumnString];
Related
I am receiving a string from server in this format:
0_1_2_3
My task is to select for digits from this string to fill four labels with them.
First idea was:
NSString *res1 = [result substringWithRange:NSMakeRange(0, 1)];
[firstLabel setText:res1];
four times with appropriate labels.
But operation will repeats many times and every time I will receive a string with increased digit values. So when every digit be a decimal this code will not work. So how can I track every digit independently from their length in a proper way?
NSString comes with a convenience method called -componentsSeparatedByString:
NSString *myString = #"0_1_2_3";
NSArray *myDigitStrings = [myString componentsSeparatedByString:#"_"];
/* access digit strings from myDigitStrings array by index or fast enumeration... */
for (NSString *myDigitString in myDigitStrings)
NSLog(#"digit string: %#", myDigitString);
I have a long string I want to retrieve from a URL and store at app launch. Later, I want to insert individual values into that string.
I'd like to do something like this:
NSString *numberLine = #"1 %# 3 %# 5 %#";
//... (later) ...
NSString *final = [NSString stringWithFormat:numberLine, #"two", #"four", #"six"];
NSLog(#"%#", final); //Should output "1 two 3 four 5 six"
I want the #"two" to be inserted into the placeholder %# that was earlier saved into numberLine.
Is there a good way to accomplish something like this?
So far my only thought is to do something like:
NSString *script = #"width = PLACEHOLDERpx";
script = [script stringByReplacingOccurrencesOfString:#"PLACEHOLDER" withString:#"12"];
What you are describing is a template. You want to leave placeholders in a string that will be filled out with data. While you could use %# and %d through a string that gets difficult as the string grows more complex. You may want to use a template library like Mustache for Objective-C. This will let you write expressions like this:
Hello {{SomeVariable}}
All you have to do is pass in an NSDictionary with keys that correspond to the data you want to render. So for the example above you might do the following:
NSString *result = [GRMustacheTemplate renderObject:[NSDictionary dictionaryWithObject:#"World" forKey:#"SomeVariable"];
fromString:#"Hello {{SomeVariable}}"
error:NULL];
This will produce a result string Hello World.
I am trying to "nicely" display fractions in my iPhone application. Previously I have been using a tedious switch statement leading to hardcoded unicode characters for the vulgar fractions, but I have learnt about the unicode fraction slash character which, if I am understanding it correctly, should mean that I can create a string as follows:
[NSString stringWithFormat:#"%i\u2044%i",numerator,denominator];
And the "renderer" will automatically print it with a smaller, superscriped numerator and subscripted denominator. However, the above code just gives me the standard 1/2 appearance. I am using drawAtPoint to put the string on the screen. I have experimented with decomposedStringUsingCanonicalMapping and precomposedStringUsingCanonicalMapping but to be honest the documentation lost me.
Should this be working or does NSString drawing not cope with this?
I happened to only want simple fractions for recipes to be converted to Unicode vulgar fractions.
Here is how you can do it:
CGFloat quantityValue = 0.25f;
NSString *quantity = nil;
if (quantityValue == 0.25f) {
// 1/4
const unichar quarter = 0xbc;
quantity = [NSString stringWithCharacters:&quarter length:1];
} else if (quantityValue == 0.33f) {
// 1/3
const unichar third = 0x2153;
quantity = [NSString stringWithCharacters:&third length:1];
} else if (quantityValue == 0.5f) {
// 1/2
const unichar half = 0xbd;
quantity = [NSString stringWithCharacters:&half length:1];
} else if (quantityValue == 0.66f) {
// 2/3
const unichar twoThirds = 0x2154;
quantity = [NSString stringWithCharacters:&twoThirds length:1];
} else if (quantityValue == 0.75f) {
// 3/4
const unichar threeQuarters = 0xbe;
quantity = [NSString stringWithCharacters:&threeQuarters length:1];
}
NSLog(#"%#", quantity);
I'm not aware of any way for a unicode character to have the properties you describe. AFAIK the only thing that distinguishes U+2044 from a regular slash is it's a bit more angled and has little-to-no space on either side, therefore making it nestle up a lot closer to the surrounding numbers.
Here's a page on using the Fraction Slash in HTML, and as you can see it demonstrates that you simply get something like "1⁄10" if you try and use it on your own. It compensates for this by using the <sup> and <sub> tags in HTML on the surrounding numbers to get an appropriate display.
In order for you to get this to work in NSString you're going to have to figure out some way to apply superscripting and subscripting to the surrounding numbers yourself.
There are some included Unicode chars that do give actual fraction appearances, but they're limited to a 1/2, a 1/3 and a 1/4 I think.
If you want this for arbitrary fractions, seems to me like you need a custom view that draws the appropriate look; either through using positioned subviews or drawRect:.
I know this was a long time ago, but if it helps, there are superscript Unicode characters for all decimal numbers you can use to display arbitrary fractions in most fonts; see answers on a similar question here - https://stackoverflow.com/a/30860163/4522315
Edit:
As per comments, this solution depends on the font you're using. Amsi Pro (left) and other commercial fonts tend to include all the required symbols for superscripts, but the system font (right) does not.
Im trying to do something that I think is super simple.
i have 3 integers - prevgues1 , 2 and 3
and i have 3 UILabels prevguess1, 2 and 3
the ints have 1 less s.
When I set the text of the label so
prevguess1.text = [NSString stringWithFormat:#"%d", prevguess1]
prevguess2.text = [NSString stringWithFormat:#"%d", prevguess2];
prevguess3.text = [NSString stringWithFormat:#"%d", prevguess3];
the label just set to a number like 89324 or something like that.
I just don't know what my problem is.
Any ideas would be helpful
Cheers
Sam
Note:
I have tried setting the text simply to a string - and have had luck.
but when i set it to a integer, which start as 0 value, (in viewdidload) the weirdness happens
prevguess1.text = [NSString stringWithFormat:#"%d", prevguess1];
Here you treat prevguess1 as a label and as an integer - probably there's a typo somewhere?
Even if it's not a matter of your problems I think you should consider changing the way you name your variables a bit to avoid possible confusion.
I have very little programming knowledge; only a fair bit in Visual Basic.
How do I take a value from a text field, then do some simple math such as divide the value by two, then display it back to the user in the same field?
In Visual Basic you could just do txtBoxOne.text = txtBoxOne.text / 2
I understand this question is more than one question and is very basic stuff, but I need to get my head out of Visual Basic and into where I should be :)
You can use doubleValue on NSString objects to retrieve the numeric value from a string.
There are variations on this, such as intValue, floatValue, boolValue, etc.
I suggest that you stick with the primitive type that has the longest range (double).
For example:
NSString *str1 = #"15";
NSString *str2 = #"5";
double result = [ str1 doubleValue ] / [ str2 doubleValue ];
NSString *str_result = [ NSString stringWithFormat: #"%f", result ];