Truncate a string and add ellipsis at the end in Objective-c - iphone

How to truncate a string in Objective-C and then add the ellipsis at the end?

NSString *origString = #"A very long string blah blah blah";
const int clipLength = 18;
if([origString length]>clipLength)
{
origString = [NSString stringWithFormat:#"%#...",[origString substringToIndex:clipLength]];
}

Use one of these NSString methods to truncate, probably the last:
– substringFromIndex:
– substringWithRange:
– substringToIndex:
and then use the NSString method
– stringByAppendingString:
to add #"..." or whatever ellopsis you like.
For example:
NSString *newString = [[string substringToIndex:12] stringByAppendingString:#"..."];
For your reading pleasure, I recommend the NSString Class Reference.

In case you wish to truncate and add ellipsis to a string with the maximum being a specific width, here is an implementation that takes into account font and size:
+ (NSString *)stringByTruncatingString: (NSString *)string toWidth: (CGFloat)width withFont: (UIFont *)font
{
#define ellipsis #"..."
NSMutableString *truncatedString = [string mutableCopy];
if ([string sizeWithAttributes: #{NSFontAttributeName: font}].width > width) {
width -= [ellipsis sizeWithAttributes: #{NSFontAttributeName: font}].width;
NSRange range = {truncatedString.length - 1, 1};
while ([truncatedString sizeWithAttributes: #{NSFontAttributeName: font}].width > width) {
[truncatedString deleteCharactersInRange:range];
range.location--;
}
[truncatedString replaceCharactersInRange:range withString:ellipsis];
}
return truncatedString;
}

Don't need chuck of code for do this..
the easiest way to do this,
for drawRect
- (void)drawRect:(NSRect)dirtyRect{
NSString *theText = #"bla blah bla bhla bla bla";
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setLineBreakMode:NSLineBreakByTruncatingTail];
[theText drawInRect:dirtyRect withAttributes:[NSDictionary dictionaryWithObjectsAndKeys:style, NSParagraphStyleAttributeName,nil]];
}
hear I use dirtyRect for String's Drawing area you can change it as you wish.
for NSTextField
NSTextField *_warningTF = [[NSTextField alloc]init];
[_warningTF setStringValue:#"sfdsf sdfdsfdsfdsfdsfdsfdsf 1234566789123456789sfdsf dsf dsfdsf"];
[_warningTF.cell setLineBreakMode:NSLineBreakByTruncatingTail];

I wrote simple category to truncate NSString by words:
#interface NSString (TFDString)
- (NSString *)truncateByWordWithLimit:(NSInteger)limit;
#end
#implementation NSString (TFDString)
- (NSString *)truncateByWordWithLimit:(NSInteger)limit {
NSRange r = NSMakeRange(0, self.length);
while (r.length > limit) {
NSRange r0 = [self rangeOfString:#" " options:NSBackwardsSearch range:r];
if (!r0.length) break;
r = NSMakeRange(0, r0.location);
}
if (r.length == self.length) return self;
return [[self substringWithRange:r] stringByAppendingString:#"..."];
}
#end
Usage:
NSString *xx = #"This string is too long, somebody just need to take and truncate it, but by word, please.";
xx = [xx truncateByWordWithLimit:50];
Result:
This string is too long, somebody just need to...
Hope it helps somebody.

the drawWithRect:options:attributes:context method helps. you can try this:
[_text drawWithRect:_textRect options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil];

Related

How to remove starting 0's in uitextfield text in iphone sdk

Code Snippet:
NSString *tempStr = self.consumerNumber.text;
if ([tempStr hasPrefix:#"0"] && [tempStr length] > 1) {
tempStr = [tempStr substringFromIndex:1];
[self.consumerNumbers addObject:tempStr];>
}
I tried those things and removing only one zero. how to remove more then one zero
Output :001600240321
Expected result :1600240321
Any help really appreciated
Thanks in advance !!!!!
Try to use this one
NSString *stringWithZeroes = #"001600240321";
NSString *cleanedString = [stringWithZeroes stringByReplacingOccurrencesOfString:#"^0+" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, stringWithZeroes.length)];
NSLog(#"Clean String %#",cleanedString);
Clean String 1600240321
convert string to int value and re-assign that value to string,
NSString *cleanString = [NSString stringWithFormat:#"%d", [string intValue]];
o/p:-1600240321
You can add a recursive function that is called until the string begin by something else than a 0 :
-(NSString*)removeZerosFromString:(NSString *)anyString
{
if ([anyString hasPrefix:#"0"] && [anyString length] > 1)
{
return [self removeZerosFromString:[anyString substringFromIndex:1]];
}
else
return anyString;
}
so you just call in your case :
NSString *tempStr = [self removeZerosFromString:#"000903123981000"];
NSString *str = #"001600240321";
NSString *newStr = [#([str integerValue]) stringValue];
If the NSString contains numbers only.
Other wise use this:
-(NSString *)stringByRemovingStartingZeros:(NSString *)string
{
NSString *newString = string;
NSInteger count = 0;
for(int i=0; i<[string length]; i++)
{
if([[NSString stringWithFormat:#"%c",[string characterAtIndex:i]] isEqualToString:#"0"])
{
newString = [newString stringByReplacingCharactersInRange:NSMakeRange(i-count, 1) withString:#""];
count++;
}
else
{
break;
}
}
return newString;
}
Simply call this method:-
NSString *stringWithZeroes = #"0000000016909tthghfghf";
NSLog(#"%#", [self stringByRemovingStartingZeros:stringWithZeroes]);
OutPut: 16909tthghfghf
Try the `stringByReplacingOccurrencesOfString´ methode like this:
NSString *new = [old stringByReplacingOccurrencesOfString: #"0" withString:#""];
SORRY: This doesn't help you due to more "0" in the middle part of your string!

How do i remove a substring from an nsstring?

Ok, say I have the string "hello my name is donald"
Now, I want to remove everything from "hello" to "is"
The thing is, "my name" could be anything, it could also be "his son"
So basically, simply doing stringByReplacingOccurrencesOfString won't work.
(I do have RegexLite)
How would I do this?
Use like below it will help you
NSString *hello = #"his is name is isName";
NSRange rangeSpace = [hello rangeOfString:#" "
options:NSBackwardsSearch];
NSRange isRange = [hello rangeOfString:#"is"
options:NSBackwardsSearch
range:NSMakeRange(0, rangeSpace.location)];
NSString *finalResult = [NSString stringWithFormat:#"%# %#",[hello substringToIndex:[hello rangeOfString:#" "].location],[hello substringFromIndex:isRange.location]];
NSLog(#"finalResult----%#",finalResult);
The following NSString Category may help you. It works good for me but not created by me. Thanks for the author.
NSString+Whitespace.h
#import <Foundation/Foundation.h>
#interface NSString (Whitespace)
- (NSString *)stringByCompressingWhitespaceTo:(NSString *)seperator;
#end
NSString+Whitespace.m
#
import "NSString+Whitespace.h"
#implementation NSString (Whitespace)
- (NSString *)stringByCompressingWhitespaceTo:(NSString *)seperator
{
//NSArray *comps = [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSArray *comps = [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSMutableArray *nonemptyComps = [[NSMutableArray alloc] init];
// only copy non-empty entries
for (NSString *oneComp in comps)
{
if (![oneComp isEqualToString:#""])
{
[nonemptyComps addObject:oneComp];
}
}
return [nonemptyComps componentsJoinedByString:seperator]; // already marked as autoreleased
}
#end
If you always know your string will begin with 'hello my name is ', then that is 17 characters, including the final space, so if you
NSString * hello = "hello my name is Donald Trump";
NSString * finalNameOnly = [hello substringFromIndex:17];

How to know the length of NSString that fits a UILabel with fixed size?

I know NSString has methods that determine the frame size for it, using NSString UIKit Additions, sizeWithFont......
How about the other way around? I mean if I have a fixed frame size, how do I know how many characters or words for a NSString that can fit into it?
If I know this, I can cut off the NSString easily.
thanks
It might not be the most elegant solution, but you could do something like this:
- (NSString *)string:(NSString *)sourceString reducedToWidth:(CGFloat)width withFont:(UIFont *)font {
if ([sourceString sizeWithFont:font].width <= width)
return sourceString;
NSMutableString *string = [NSMutableString string];
for (NSInteger i = 0; i < [sourceString length]; i++) {
[string appendString:[sourceString substringWithRange:NSMakeRange(i, 1)]];
if ([string sizeWithFont:font].width > width) {
if ([string length] == 1)
return nil;
[string deleteCharactersInRange:NSMakeRange(i, 1)];
break;
}
}
return string;
}
Then call it like this:
NSString *test = #"Hello, World!";
CGFloat width = 40.0;
UIFont *font = [UIFont systemFontOfSize:[UIFont labelFontSize]];
NSString *reducedString = [self string:test reducedToWidth:width withFont:font];
NSLog(#"%#", reducedString);
You cannot know/determine the number of characters that fits in a UILabel with fixed width because some characters are smaler than others, eg l and m.
There are two options:
Use Mono-Space-Fonts (each character has also a fixed width). Then determine the width for one char in your font with your font-size and calculate the number of chars
Allow any number of characters and check on insert if the inserted characters fit.
You have to know what behaviour you want to have. What should happen if there is text that does not fit. If you only want to truncate (like the solution of mortenfast does) then just use UILineBreakModeTailTruncation for the lineBreakMode-property of your UILabel (there are more options, like TruncateHead, Clip, Word Wrap)
Or you just just use the lineBreak property and set it to NSLineBreakByCharWrapping and move on with your life. https://stackoverflow.com/a/29088337/951349
Thanks #Morten. I've updated the sample code to handle word separation. It also eliminates extra spaces in between words. It has not been tested in the field, but my tests have, thus far, proven OK. Please update at your leisure if you find improvements or bug/glitch fixes.
-(NSString*)string:(NSString*)sourceString reducedToWidth:(CGFloat)width withFont:(UIFont*)font {
// if full string is within bounds, simply return the full string
if( [sourceString sizeWithFont:font].width <= width ) return sourceString;
// break up string into words. if <= 1 word, return original string
NSArray* words = [sourceString componentsSeparatedByString:#" "];
NSInteger numWords = [words count];
if( numWords <= 1 ) return sourceString;
// our return var. we populate as we go
NSMutableString* str = [NSMutableString string];
// temp var to test with before adding to return string
NSMutableString* strTemp = [NSMutableString string];
// string to hold word LESS spaces
NSString* strWordTemp = nil;
// the word we're currently on
NSInteger numWord = 0;
// whether we need to add a space (when not last word)
Boolean addSpace = NO;
// loop through our words....
for( NSString* strWord in words ) {
// which word we're on
numWord++;
// eliminate white space
strWordTemp = [strWord stringByReplacingOccurrencesOfString:#" " withString:#""];
// if this word is empty or was a space(s), skip it
if( [strWordTemp isEqualToString:#""] ) continue;
// append to temp string
[strTemp appendString:strWordTemp];
// if we're still within the bounds...
if( [strTemp sizeWithFont:font].width <= width ) {
// default = no extra space
addSpace = NO;
// if we're not the last word, add a space & check for length
if( numWord < numWords ) {
[strTemp appendString:#" "];
// if adding space made it too long, then just don't add it!
if( [strTemp sizeWithFont:font].width > width ) {
// it was too long with space, so we'll just add word
[str appendString:strWordTemp];
break;
}
// otherwise, it's OK to add the space
else addSpace = YES;
}
// append to return string and continue
[str appendFormat:#"%#%#", strWordTemp, ( addSpace ? #" " : #"" )];
}
// otherwise, we're done
else break;
}
// return our result
return str;
}

how to remove () charracter

when i convert my array by following method , it adds () charracter.
i want to remove the () how can i do it..
NSMutableArray *rowsToBeDeleted = [[NSMutableArray alloc] init];
NSString *postString =
[NSString stringWithFormat:#"%#",
rowsToBeDeleted];
int index = 0;
for (NSNumber *rowSelected in selectedArray)
{
if ([rowSelected boolValue])
{
profileName = [appDelegate.archivedItemsList objectAtIndex:index];
NSString *res = [NSString stringWithFormat:#"%d",profileName.userID];
[rowsToBeDeleted addObject:res];
}
index++;
}
UPDATE - 1
when i print my array it shows like this
(
70,
71,
72
)
Here's a brief example of deleting the given characters from a string.
NSString *someString = #"(whatever)";
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:#"()"];
NSMutableString *mutableCopy = [NSMutableString stringWithString:someString];
NSRange range;
for (range = [mutableCopy rangeOfCharacterFromSet:charSet];
range.location != NSNotFound;
[mutableCopy deleteCharactersInRange:range],
range = [mutableCopy rangeOfCharacterFromSet:charSet]);
All this does is get a mutable copy of the string, set up a character set with any and all characters to be stripped from the string, and find and remove each instance of those characters from the mutable copy. This might not be the cleanest way to do it (I don't know what the cleanest is) - obviously, you have the option of doing it Ziminji's way as well. Also, I abused a for loop for the hell of it. Anyway, that deletes some characters from a string and is pretty simple.
Try using NSArray’s componentsJoinedByString method to convert your array to a string:
[rowsToBeDeleted componentsJoinedByString:#", "];
The reason you are getting the parenthesis is because you are calling the toString method on the NSArray class. Therefore, it sounds like you just want to substring the resulting string. To do this, you can use a function like the following:
+ (NSString *) extractString: (NSString *)string prefix: (NSString *)prefix suffix: (NSString *)suffix {
int strLength = [string length];
int begIndex = [prefix length];
int endIndex = strLength - (begIndex + [suffix length]);
if (endIndex > 0) {
string = [string substringWithRange: NSMakeRange(begIndex, endIndex)];
}
return string;
}

iphone string initial char before space

I have a question...
I wish take from a string that contains a name and surname, the initial of the first and the surname complete....
example:
NSString* myName = #"Mel Gibson";
//I Wish have "M Gibson";
NSString* myName2 = #"Leonardo Di Caprio";
//I wish have "L Di Caprio";
Thanks
#implementation NSString (AbbreviateFirstWord)
-(NSString*)stringByAbbreviatingFirstWord {
// step 1: Locate the white space.
NSRange whiteSpaceLoc = [self rangeOfString:#" "];
if (whiteSpaceLoc.location == NSNotFound)
return self;
// step 2: Remove all characters between the first letter and the white space.
NSRange rangeToRemove = NSMakeRange(1, whiteSpaceLoc.location - 1);
return [self stringByReplacingCharactersInRange:rangeToRemove withString:#""];
}
#end