简体   繁体   中英

How do I add spaces after a string

I am wanting to add spaces after a string in objective c....so I can perform some padding.

I have viewed the method at this question - How can I add leading whitespace in front of the NSString?

But it only seems to work for spaces in front of a NSString.

Edit: These don't seem to be working, here is some information.

I am performing this inside - (void)tableView: (UITableView*)tableView willDisplayCell: (UITableViewCell*)cell forRowAtIndexPath: (NSIndexPath*)indexPath - Where I have an image being displayed also to the right of the text. But my text is too close to the image. I know I can create a UITextView to deal with this, but this then leads to other issues. Hence the spaces at the end of the text being the simplest solution....but this does not seem to work inside a cell.

You can adapt the answer you found very quickly to get the answer you want.

#import <Foundation/Foundation.h>
#include <stdlib.h>

int main()
{
    int maxLength = 5;
    NSString *text = @"xml";
    NSLog(@"Text:\"%@\"", text);

    NSString *result = [text stringByPaddingToLength:MAX(maxLength, text.length)
                                          withString:@" " startingAtIndex:0];
    NSLog(@"Result:\"%@\"", result);
    return 0;
}

I've created an SSCCE and added logs to show that this method works.

2014-09-07 16:25:06.713 a.out[29685:507] Text:"xml"
2014-09-07 16:25:06.714 a.out[29685:507] Result:"xml  "

Another simple technique

NSString *yourString = @"Objective-c is easy";    
NSString *spaceString = @"       ";
NSString *finalString = [NSString stringWithFormat:@"%@%@",yourString,spaceString];

check this:

int maxLength = 5;
NSString *text = @"abc";
if (text.length < maxLength) {
    text = [text stringByPaddingToLength:maxLength withString:@" " startingAtIndex:0];
}
// result: @"abc  "

尝试这个:

YourString = [YourString stringByAppendingString:@" "];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM