Remove last character of NSString - objective-c

I've got some trouble 'ere trying to remove the last character of an NSString.
I'm kinda newbie in Objective-C and I have no idea how to make this work.
Could you guys light me up?

NSString *newString = [oldString substringToIndex:[oldString length]-1];
Always refer to the documentation:
substringToIndex:
length
To include code relevant to your case:
NSString *str = textField.text;
NSString *truncatedString = [str substringToIndex:[str length]-1];

Try this:
s = [s substringToIndex:[s length] - 1];

NSString *string = [NSString stringWithString:#"ABCDEF"];
NSString *newString = [string substringToIndex:[string length]-1];
NSLog(#"%#",newString);
You can see = ABCDE

NSString = *string = #"abcdef";
string = [string substringToIndex:string.length-(string.length>0)];
If there is a character to delete (i.e. the length of the string is greater than 0)
(string.length>0) returns 1, thus making the code return:
string = [string substringToIndex:string.length-1];
If there is NOT a character to delete (i.e. the length of the string is NOT greater than 0)
(string.length>0) returns 0, thus making the code return:
string = [string substringToIndex:string.length-0];
which prevents crashes.

This code will just return the last character of the string and not removing it :
NSString *newString = [oldString substringToIndex:[oldString length]-1];
you may use this instead to remove the last character and retain the remaining values of a string :
str = [str substringWithRange:NSMakeRange(0,[str length] - 1)];
and also using substringToIndex to a NSString with 0 length will result to crashes.
you should add validation before doing so, like this :
if ([str length] > 0) {
str = [str substringToIndex:[s length] - 1];
}
with this, it is safe to use substring method.
NOTE : Apple will reject your application if it is vulnerable to crashes.

Simple and Best Approach
[mutableString deleteCharactersInRange:NSMakeRange([myRequestString length]-1, 1)];

Related

How to remove the first space from the NSString?

I want to remove only first space in below string.
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
Note: There is a space after IF_Distance and another space after
GET_Mi. I am unable to remove the space after IF_Distance.
Use rangeOfString: to locate the first space, then use stringByReplacingCharactersInRange:withString: to replace it with the empty string.
Remove space by using below code.
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *secondString = [str stringByReplacingOccurrencesOfString:#"IF_Distance " withString:#"IF_Distance"];
Try This:
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *firstStringContainingSpace = [[str componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] firstObject];//firstStringContainingSpace = IF_Distance
str = [str stringByReplacingCharactersInRange:[str rangeOfString:[NSString stringWithFormat:#"%# ",firstStringContainingSpace]] withString:firstStringContainingSpace];
Output:
str = #"IF_Distance(GET_Mi mi=km*1.4,STRING1,STRING2)";
You can remove first space by using following code:
First find space by using rangeOfString: and then remove by using stringByReplacingCharactersInRange:withString: method.
Like,
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *strSpace = #" ";
NSRange range = [str rangeOfString:strSpace];
NSString *strFinal;
if (NSNotFound != range.location) {
strFinal = [str stringByReplacingCharactersInRange:range withString:#""];
}
If you are looking for some more universal way - this is the variant of it:
- (NSString *)removeWhitespaces:(NSString *)string {
NSMutableArray * stringComponents = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] mutableCopy];
NSString * fStringComponent = [stringComponents firstObject];
[stringComponents removeObject:fStringComponent];
return [fStringComponent stringByAppendingString:[stringComponents componentsJoinedByString:#" "]];
}

Check if NSString only contains one character repeated

I want to know a simple and fast way to determine if all characters in an NSString are the same.
For example:
NSString *string = "aaaaaaaaa"
=> return YES
NSString *string = "aaaaaaabb"
=> return NO
I know that I can achieve it by using a loop but my NSString is long so I prefer a shorter and simpler way.
you can use this, replace first character with null and check lenght:
-(BOOL)sameCharsInString:(NSString *)str{
if ([str length] == 0 ) return NO;
return [[str stringByReplacingOccurrencesOfString:[str substringToIndex:1] withString:#""] length] == 0 ? YES : NO;
}
Here are two possibilities that fail as quickly as possible and don't (explicitly) create copies of the original string, which should be advantageous since you said the string was large.
First, use NSScanner to repeatedly try to read the first character in the string. If the loop ends before the scanner has reached the end of the string, there are other characters present.
NSScanner * scanner = [NSScanner scannerWithString:s];
NSString * firstChar = [s substringWithRange:[s rangeOfComposedCharacterSequenceAtIndex:0]];
while( [scanner scanString:firstChar intoString:NULL] ) continue;
BOOL stringContainsOnlyOneCharacter = [scanner isAtEnd];
Regex is also a good tool for this problem, since "a character followed by any number of repetitions of that character" is in very simply expressed with a single back reference:
// Match one of any character at the start of the string,
// followed by any number of repetitions of that same character
// until the end of the string.
NSString * patt = #"^(.)\\1*$";
NSRegularExpression * regEx =
[NSRegularExpression regularExpressionWithPattern:patt
options:0
error:NULL];
NSArray * matches = [regEx matchesInString:s
options:0
range:(NSRange){0, [s length]}];
BOOL stringContainsOnlyOneCharacter = ([matches count] == 1);
Both these options correctly deal with multi-byte and composed characters; the regex version also does not require an explicit check for the empty string.
use this loop:
NSString *firstChar = [str substringWithRange:NSMakeRange(0, 1)];
for (int i = 1; i < [str length]; i++) {
NSString *ch = [str substringWithRange:NSMakeRange(i, 1)];
if(![ch isEqualToString:firstChar])
{
return NO;
}
}
return YES;

NSString by removing the initial zeros?

How can I remove leading zeros from an NSString?
e.g. I have:
NSString *myString;
with values such as #"0002060", #"00236" and #"21456".
I want to remove any leading zeros if they occur:
e.g. Convert the previous to #"2060", #"236" and #"21456".
Thanks.
For smaller numbers:
NSString *str = #"000123";
NSString *clean = [NSString stringWithFormat:#"%d", [str intValue]];
For numbers exceeding int32 range:
NSString *str = #"100004378121454";
NSString *clean = [NSString stringWithFormat:#"%d", [str longLongValue]];
This is actually a case that is perfectly suited for regular expressions:
NSString *str = #"00000123";
NSString *cleaned = [str stringByReplacingOccurrencesOfString:#"^0+"
withString:#""
options:NSRegularExpressionSearch
range:NSMakeRange(0, str.length)];
Only one line of code (in a logical sense, line breaks added for clarity) and there are no limits on the number of characters it handles.
A brief explanation of the regular expression pattern:
The ^ means that the pattern should be anchored to the beginning of the string. We need that to ensure it doesn't match legitimate zeroes inside the sequence of digits.
The 0+ part means that it should match one or more zeroes.
Put together, it matches a sequence of one or more zeroes at the beginning of the string, then replaces that with an empty string - i.e., it deletes the leading zeroes.
The following method also gives the output.
NSString *test = #"0005603235644056";
// Skip leading zeros
NSScanner *scanner = [NSScanner scannerWithString:test];
NSCharacterSet *zeros = [NSCharacterSet
characterSetWithCharactersInString:#"0"];
[scanner scanCharactersFromSet:zeros intoString:NULL];
// Get the rest of the string and log it
NSString *result = [test substringFromIndex:[scanner scanLocation]];
NSLog(#"%# reduced to %#", test, result);
- (NSString *) removeLeadingZeros:(NSString *)Instring
{
NSString *str2 =Instring ;
for (int index=0; index<[str2 length]; index++)
{
if([str2 hasPrefix:#"0"])
str2 =[str2 substringFromIndex:1];
else
break;
}
return str2;
}
In addition to adali's answer, you can do the following if you're worried about the string being too long (i.e. greater than 9 characters):
NSString *str = #"000200001111111";
NSString *strippedStr = [NSString stringWithFormat:#"%lld", [temp longLongValue]];
This will give you the result: 200001111111
Otherwise, [NSString stringWithFormat:#"%d", [temp intValue]] will probably return 2147483647 because of overflow.

Replace characters in NSString

I am trying to replace all characters except last 4 in a String with *'s.
In objective-c there is a method in NSString class replaceStringWithCharactersInRange: withString: where I would give it range (0,[string length]-4) ) with string #"*". This is what it does: 123456789ABCD is modified to *ABCD while I am looking to make ********ABCD.
I understand that it replaced range I specified with string object. How to accomplish this ?
NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\\d" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *newString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:#"*"];
This looks like a simple problem... get the first part string and return it with the last four characters appended to it.
Here is a function that returns the needed string :
-(NSString *)neededStringWithString:(NSString *)aString {
// if the string has less than or 4 characters, return nil
if([aString length] <= 4) {
return nil;
}
NSUInteger countOfCharToReplace = [aString length] - 4;
NSString *firstPart = #"*";
while(--countOfCharToReplace) {
firstPart = [firstPart stringByAppendingString:#"*"];
}
// range for the last four
NSRange lastFourRange = NSMakeRange([aString length] - 4, 4);
// return the combined string
return [firstPart stringByAppendingString:
[aString substringWithRange:lastFourRange]];
}
The most unintuitive part in Cocoa is creating the repeating stars without some kind of awkward looping. stringByPaddingToLength:withString:startingAtIndex: allows you to create a repeating string of any length you like, so once you have that, here's a simple solution:
NSInteger starUpTo = [string length] - 4;
if (starUpTo > 0) {
NSString *stars = [#"" stringByPaddingToLength:starUpTo withString:#"*" startingAtIndex:0];
return [string stringByReplacingCharactersInRange:NSMakeRange(0, starUpTo) withString:stars];
} else {
return string;
}
I'm not sure why the accepted answer was accepted, since it only works if everything but last 4 is a digit. Here's a simple way:
NSMutableString * str1 = [[NSMutableString alloc]initWithString:#"1234567890ABCD"];
NSRange r = NSMakeRange(0, [str1 length] - 4);
[str1 replaceCharactersInRange:r withString:[[NSString string] stringByPaddingToLength:r.length withString:#"*" startingAtIndex:0]];
NSLog(#"%#",str1);
You could use [theString substringToIndex:[theString length]-4] to get the first part of the string and then combine [theString length]-4 *'s with the second part. Perhaps their is an easier way to do this..
NSMutableString * str1 = [[NSMutableString alloc]initWithString:#"1234567890ABCD"];
[str1 replaceCharactersInRange:NSMakeRange(0, [str1 length] - 4) withString:#"*"];
NSLog(#"%#",str1);
it works
The regexp didn't work on iOS7, but perhaps this helps:
- (NSString *)encryptString:(NSString *)pass {
NSMutableString *secret = [NSMutableString new];
for (int i=0; i<[pass length]; i++) {
[secret appendString:#"*"];
}
return secret;
}
In your case you should stop replacing the last 4 characters. Bit crude, but gets the job done

How to get the first N words from a NSString in Objective-C?

What's the simplest way, given a string:
NSString *str = #"Some really really long string is here and I just want the first 10 words, for example";
to result in an NSString with the first N (e.g., 10) words?
EDIT: I'd also like to make sure it doesn't fail if the str is shorter than N.
If the words are space-separated:
NSInteger nWords = 10;
NSRange wordRange = NSMakeRange(0, nWords);
NSArray *firstWords = [[str componentsSeparatedByString:#" "] subarrayWithRange:wordRange];
if you want to break on all whitespace:
NSCharacterSet *delimiterCharacterSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSArray *firstWords = [[str componentsSeparatedByCharactersInSet:delimiterCharacterSet] subarrayWithRange:wordRange];
Then,
NSString *result = [firstWords componentsJoinedByString:#" "];
While Barry Wark's code works well for English, it is not the preferred way to detect word breaks. Many languages, such as Chinese and Japanese, do not separate words using spaces. And German, for example, has many compounds that are difficult to separate correctly.
What you want to use is CFStringTokenizer:
CFStringRef string; // Get string from somewhere
CFLocaleRef locale = CFLocaleCopyCurrent();
CFStringTokenizerRef tokenizer = CFStringTokenizerCreate(kCFAllocatorDefault, string, CFRangeMake(0, CFStringGetLength(string)), kCFStringTokenizerUnitWord, locale);
CFStringTokenizerTokenType tokenType = kCFStringTokenizerTokenNone;
unsigned tokensFound = 0, desiredTokens = 10; // or the desired number of tokens
while(kCFStringTokenizerTokenNone != (tokenType = CFStringTokenizerAdvanceToNextToken(tokenizer)) && tokensFound < desiredTokens) {
CFRange tokenRange = CFStringTokenizerGetCurrentTokenRange(tokenizer);
CFStringRef tokenValue = CFStringCreateWithSubstring(kCFAllocatorDefault, string, tokenRange);
// Do something with the token
CFShow(tokenValue);
CFRelease(tokenValue);
++tokensFound;
}
// Clean up
CFRelease(tokenizer);
CFRelease(locale);
Based on Barry's answer, I wrote a function for the sake of this page (still giving him credit on SO)
+ (NSString*)firstWords:(NSString*)theStr howMany:(NSInteger)maxWords {
NSArray *theWords = [theStr componentsSeparatedByString:#" "];
if ([theWords count] < maxWords) {
maxWords = [theWords count];
}
NSRange wordRange = NSMakeRange(0, maxWords - 1);
NSArray *firstWords = [theWords subarrayWithRange:wordRange];
return [firstWords componentsJoinedByString:#" "];
}
Here's my solution, derived from the answers given here, for my own problem of removing the first word from a string...
NSMutableArray *words = [NSMutableArray arrayWithArray:[lowerString componentsSeparatedByString:#" "]];
[words removeObjectAtIndex:0];
return [words componentsJoinedByString:#" "];