Padding NSString not working - objective-c

I have read that to left-pad an NSString all you need to do is this:
NSString *paddedStr = [NSString stringWithFormat:#"%-20.20# %-20.20#",
aString, anotherSting];
But, that does not work !! I donĀ“t know why. I have tried a lot of combinations without success. Examples:
NSString *paddedStr = [NSString stringWithFormat:#"%-20s#", " ", myString];
but that way is ugly and ... ugly. It just append 20 times the char (" ") before the string (myString) and that is not what we need right?
The goal is to have an NSString formatted to present two or more columns of 20 chars each one no matter the length of the string within a row.
Example Goal Output:
Day Hour Name Age
Does anybody know how to do this right?
I'm using ARC and iOS 5.
And actually, the formatted string is going to be written to file using NSFileHandle.
Thanks to all of you folks !!
Edit:
I have noticed that this works:
NSString *str = [NSString stringWithFormat:#"%-10.10s %-10.10s",
[strOne UTF8String], [strTwo UTF8String]];
But... We don't want C-style strings either.

Here is a way to do that :
NSString *paddedStr = [NSString stringWithFormat:#"%#%#",
[#"day" stringByPaddingToLength:20
withString:#" "
startingAtIndex:0],
[#"Hour" stringByPaddingToLength:20
withString:#" "
startingAtIndex:0]];

Related

getting NSArray length/count - Objective C

Well I've looked at similar problems over the site but haven't reached a solution thus far so I must be doing something wrong.
Essentially, I am importing a text file, then splitting each line into an element of an array. Since the text file will be updated etc.. I won't every know the exact amount of lines in the file and therefore how many elements in the array. I know in Java you can do .length() etc.. and supposedly in Objective C you can use 'count' but i'm having no luck returning the length of my array... suggestions?
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"allshows"
ofType:#"txt"];
NSString *fileString = [NSString stringWithContentsOfFile:filePath];
NSArray *lines = [fileString componentsSeparatedByString:#"\n"];
NSUInteger *elements = [lines count];
NSLog(#"Number of Shows : ", elements);
and what is being output is NOTHING. as in "Number of Shows : " - blank, like it didn't even count at all.
Thank you for any help!
You're missing the format string placeholder. It should be:
NSLog(#"Number of shows: %lu", elements);
You need to use a format specifier to print an integer (%d):
NSLog(#"Number of Shows : %d", elements);
Looking at your other post, it seems like you are a Java developer. In Java's System.out, you just append the variables. In Objective-C, I suggest you look at "print format specifiers". Objective-C uses the same format.

\n does not skip to next line in NSString

NSMutableString *a = #"Hi";
NSMutableString *b =[a stringByAppendingString:#"\n\n Hi Again"];
The above doesn't give an error but does not put "Hi Again" on the next line. Why?
EDIT2
I realised after posting, that the OP had NSString in the title but put NSMutableString in the code. I have submitted an edit to change the NSMutableString to NSString.
I will leave this as it still maybe helpful.
Well I am surprised that does not give an error, because you are giving a NSMutableString a NSString.
You need to read the Documentation on NSMutableStrings.
to give you an idea
//non mutable strings
NSString *shortGreetingString = #"Hi";
NSString *longGreetingString = #"Hi Again";
/*mutable string - is created and given a character capacity The number of characters indicated by capacity is simply a hint to increase the efficiency of data storage. The value does not limit the length of the string
*/
NSMutableString *mutableString= [NSMutableString stringWithCapacity:15];
/*The mutableString, now uses an appendFormat to construct the string
each %# in the Parameters for the appendFormat is a place holder for values of NSStrings
listed in the order you want after the comma.
Any other charactars will be included in the construction, in this case the new lines.
*/
[mutableString appendFormat:#"%#\n\n%#",shortGreetingString,longGreetingString];
NSLog (#"mutableString = %#" ,mutableString);
[pool drain];
I think this might help you. You'd rather to use '\r' instead of '\n'
I also had a similar problem and found \n works in LLDB but not in GDB
Try using NSString. You could use:
NSString *a = [NSString stringWithFormat:#"%#\n\n%#", #"Hi", #"Hello again"]
If your string is going in a UIView (e.g a UILabel), you also need to set the number of lines to 0
myView.numberOfLines=0;

How to remove first 3 characters from NSString?

I have a string like this "A. rahul VyAs"
and i want to remove "A. " and the space after the "A." so that new string would be "rahul VyAs"
How do i achieve this?
You can use the NSString instance methods substringWithRange: or substringFromIndex:
NSString *str = #"A. rahul VyAs";
NSString *newStr = [str substringWithRange:NSMakeRange(3, [str length]-3)];
or
NSString *str = #"A. rahul VyAs";
NSString *newStr = [str substringFromIndex:3];
This is a solution I have seen specifically for removing regularly occurring prefixes and solving the answer to the question How do I remove "A. "?
NSString * name = #"A. rahul VyAs";
NSString * prefixToRemove = #"A. ";
name = [name stringByReplacingOccurrencesOfString:prefixToRemove withString:#""];
This code will remove what you tell it to remove/change if the character set exists, such as "A. ", even if the three characters (or more/less) are in the middle of the string.
If you wanted to remove rahul, you can. It's diverse in that you specify exactly what you want removed or changed, and if it exists anywhere in the String, it will be removed or changed.
If you only want a certain specified number of characters removed from the front of the text that are always random or unknown, use the [string length] method as is the top answer.
If you want to remove or change certain characters that repeatedly appear, the method I have used will enable that, similar to Wordsearch on document editors.
Try this,
char *string=[#"A. rahul VyAs" cStringUsingEncoding:NSUTF8StringEncoding];
char *subString=&name[3];
NSString *newString=[NSString stringWithCString:subString encoding:NSUTF8StringEncoding];
It's this simple:
myString = [myString subStringFromIndex:3]
That's it.

simple question concerning NSString adding multiple strings

I have a fairly simple question concerning NSString however it doesn't seem to do what I want.
this is what i have
NSString *title = [NSString stringWithformat: character.name, #"is the character"];
This is a line in my parser takes the charactername and inserts in into a plist , however it doesn't insert the #"is the character" is there something I'm doing wrong?
Your code is wrong. It should be :
NSString *title
= [NSString stringWithformat:#"%# is the character", character.name];
assuming that character.name is another NSString.
Read the Formatting String Objects paragraph of the String Programming Guide for Cocoa to learn everything about formatting strings.
stringWithFormat takes a format string as the first argument so, assuming character.name is the name of your character, you need:
NSString *title = [NSString stringWithformat: #"%s is the character",
character.name];
What you have is the character name as the format string so, if it's #"Bob" then Bob is what you'll get. If it was "#Bob %s", that would work but would probably stuff up somewhere else that you display just the character name :-)
Note that you should use "%s" for a C string, I think "%#" is the correct format specifier if character.name is an NSString itself.

How to add percent sign to NSString

I want to have a percentage sign in my string after a digit. Something like this: 75%.
How can I have this done? I tried:
[NSString stringWithFormat:#"%d\%", someDigit];
But it didn't work for me.
The code for percent sign in NSString format is %%. This is also true for NSLog() and printf() formats.
The escape code for a percent sign is "%%", so your code would look like this
[NSString stringWithFormat:#"%d%%", someDigit];
Also, all the other format specifiers can be found at Conceptual Strings Articles
If that helps in some cases, it is possible to use the unicode character:
NSLog(#"Test percentage \uFF05");
The accepted answer doesn't work for UILocalNotification. For some reason, %%%% (4 percent signs) or the unicode character '\uFF05' only work for this.
So to recap, when formatting your string you may use %%. However, if your string is part of a UILocalNotification, use %%%% or \uFF05.
seems if %% followed with a %#, the NSString will go to some strange codes
try this and this worked for me
NSString *str = [NSString stringWithFormat:#"%#%#%#", #"%%",
[textfield text], #"%%"];
uese following code.
NSString *searchText = #"Bhupi"
NSString *formatedSearchText = [NSString stringWithFormat:#"%%%#%%",searchText];
will output: %Bhupi%
iOS 9.2.1, Xcode 7.2.1, ARC enabled
You can always append the '%' by itself without any other format specifiers in the string you are appending, like so...
int test = 10;
NSString *stringTest = [NSString stringWithFormat:#"%d", test];
stringTest = [stringTest stringByAppendingString:#"%"];
NSLog(#"%#", stringTest);
For iOS7.0+
To expand the answer to other characters that might cause you conflict you may choose to use:
- (NSString *)stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet *)allowedCharacters
Written out step by step it looks like this:
int test = 10;
NSString *stringTest = [NSString stringWithFormat:#"%d", test];
stringTest = [[stringTest stringByAppendingString:#"%"]
stringByAddingPercentEncodingWithAllowedCharacters:
[NSCharacterSet alphanumericCharacterSet]];
stringTest = [stringTest stringByRemovingPercentEncoding];
NSLog(#"percent value of test: %#", stringTest);
Or short hand:
NSLog(#"percent value of test: %#", [[[[NSString stringWithFormat:#"%d", test]
stringByAppendingString:#"%"] stringByAddingPercentEncodingWithAllowedCharacters:
[NSCharacterSet alphanumericCharacterSet]] stringByRemovingPercentEncoding]);
Thanks to all the original contributors. Hope this helps. Cheers!