Add space in NSString?

cocoa, cocoa-touch, ios, objective-c

Solution

You can use `stringByPaddingToLength` function to add spaces anywhere in string. Check following sample function for the same.

-(NSString*)stringByAddingSpace:(NSString*)stringToAddSpace spaceCount:(NSInteger)spaceCount atIndex:(NSInteger)index{
    NSString *result = [NSString stringWithFormat:@"%@%@",[@" " stringByPaddingToLength:spaceCount withString:@" " startingAtIndex:0],stringToAddSpace];
    return result;
}

Sample usage in your case:

NSString *spaceAddedText = [self stringByAddingSpace:@"Hello World!" spaceCount:5 atIndex:0]
NSString *postText = [NSString stringWithFormat:@"%@%@",spaceAddedText,myPointer];

Problem

Basically, I have a share button that pulls up a compose email modal view. I want to add a tab space in my NSStringWithFormat. Lets call it "postText". When I try to set a space like this: `NSString *postText = [NSString stringWithFormat:@"\tHello, World! %@",myPointer];` it doesn't insert anything (It returns "Hello, World! myPointerValue"), and if I just use tab, it messes up the spacing because I need to use tab about 10-20 times. Am I doing something wrong?

Original source