Ritika
Ritika

Reputation: 593

Truncate Substring from middle for NSString

How can we truncate substring from NSString from middle Let say, i have NSString NSString *str = @"Thu 25 Nov 2014 /Shared/Documents/Drawing/c" I want to truncate path string from middle & show that on label.For This i am using NSStrinbuteString on label

NSString *path = @"/Shared/Documents/Drawing/c";
NSString *date = @"Thu 25 Nov 2014";
NSString *wholeString = self.descLabel.text;
NSRange pathRange = [wholeString rangeOfString:path];
NSRange range=NSMakeRange(pathRange.location,path.length);

NSMutableParagraphStyle* style= [NSMutableParagraphStyle new];
style.lineBreakMode= NSLineBreakByTruncatingMiddle;


NSMutableAttributedString* str=[[NSMutableAttributedString alloc]initWithString: self.descLabel.text];
[str addAttribute: NSParagraphStyleAttributeName value: style range: range];
self.descLabel.attributedText= str;

This doesnt seems to be doing anything.Cn anyone suggest if i am doing something wrong

Upvotes: 0

Views: 571

Answers (1)

Widerberg
Widerberg

Reputation: 1138

A not so optimized example using very simple regex. This example requires the path to start with a forward slash and also that the path always is last.

NSString *test = @"Thu 25 Nov 2014 /Shared/Documents/Drawing/c";
NSString *resultPath = @"";
// Create a range for it. We do the replacement on the whole
// range of the text, not only a portion of it. This can be optimized.
NSRange range = NSMakeRange(0, test.length);

NSError *errors = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(/.*)" options:NSRegularExpressionCaseInsensitive|NSRegularExpressionDotMatchesLineSeparators error:&errors];

NSArray *matches = [regex matchesInString:test options:NSMatchingProgress range:range];
if(matches.count == 1 && !errors) {
    NSTextCheckingResult* result = matches[0];
    // One result found
    resultPath = [test substringWithRange:result.range];
} else {
    // many results found or error
}

resultPath will now contain: "/Shared/Documents/Drawing/c".

Now you can simply add the result to your label or add it to an attributed string for more customization abilities like you already have done.

As i said in the beginning. This is one very basic regex example..

Upvotes: 1

Related Questions