I have a string
string = "01";
but I want to delete the '0' and have a new string with only '1'. Is there a fast solution?
-(NSString *) substringFromIndex: i
Returns a substring from the character at i to the end
-(NSString *) substringWithRange: range
Returns a substring based on a specified range
-(NSString *) substringToIndex: i
Returns a substring from the start of the string up to the character at index i
And if you only want to remove 0's before any nonzero value then make a
int i = [str intValue];
str = [NSString stringWithFormat:#"%d",i];
You can use this:-
NSString *string=#"01";
NSString *temp=[string substringWithRange:NSMakeRange(1, 1)];
NSLog(#"temp%#",temp);
If you want to remove the leading zero from an arbitrary length NSString object you could do:
NSRange aRange;
aRange.location = 0;
aRange.length = 1;
[theBreakerCode stringByReplacingOccurrencesOfString:#"0" withString:#"" options:NSLiteralSearch range:aRange];
Strings without a leading zero are untouched.
Related
I want to allow only specific characters for a string.
Here's what I've tried.
NSString *mdn = #"010-222-1111";
NSCharacterSet *allowedCharacterSet = [NSCharacterSet characterSetWithCharactersInString:#"+0123456789"];
NSString *trimmed = [mdn stringByTrimmingCharactersInSet:[allowedCharacterSet invertedSet]];
NSString *replaced = [mdn stringByReplacingOccurrencesOfString:#"-" withString:#""];
The result of above code is as below. The result of replaced is what I want.
trimmed : 010-222-1111
replaced : 0102221111
What am I missing here? Why doesn't invertedSet work?
One more weird thing here. If I removed the invertedSet part like
NSString *trimmed = [mdn stringByTrimmingCharactersInSet:allowedCharacterSet];
The result is
trimmed : -222-
I have no idea what makes this result.
stringByTrimmingCharactersInSet: only removes occurrences in the beginning and the end of the string. That´s why when you take inverted set, no feasible characters are found in the beginning and end of the string and thus aren't removed either.
A solution would be:
- (NSString *)stringByRemovingCharacters:(NSString*)str inSet:(NSCharacterSet *)characterSet {
return [[str componentsSeparatedByCharactersInSet:characterSet] componentsJoinedByString:#""];
}
stringByTrimmingCharactersInSet is only removing chars at the end and the beginning of the string, which results in -222-. You have to do a little trick to remove all chars in the set
NSString *newString = [[origString componentsSeparatedByCharactersInSet:
[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
componentsJoinedByString:#""];
I want to read a string of type "t = 10" in Obj C, and take the value of the character and the value of the integer. What is the best way to do that?
You can use NSScanner for that:
NSScanner *scn = [NSScanner scannerWithString:#"t = 10"];
NSString *theChar;
[scn scanUpToString:#" = " intoString:&theChar];
[scn scanString:#" = " intoString:NULL];
int n;
[scn scanInt:&n];
here theChar will contain an NSString object containing the char and n will contain the numerical value of the integer.
Take a look at strtok, which is part of the C standard library.
It's slightly complicated, but should do a good portion of your work for you.
The "t", "=", and "10" are what the docs refer to as "tokens", whereas the whitespace is the "separator".
If you don't care about the "=", you could have strtok treat that as a separator, too.
you can convert your string to NSArray
// separate the string to array by the = sign
NSArray *myArray = [myString componentsSeparatedByString:#"="]
// get the character
NSString *character = [myArray ObjectAtIndex:0];
// remove the whitespaces from the character
character = [character stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
// get the value
NSString *value= [myArray ObjectAtIndex:1];
// remove the whitespaces from the value
value= [value stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
hope it helps :)
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.
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)];
How do I test if the last character of an NSString is a whitespace or newline character.
I could do [[NSCharacter whitespaceAndNewlineCharacterSet] characterIsMember:lastChar]. But, how do I get the last character of an NSString?
Or, should I just use - [NSString rangeOfCharacterFromSet:options:] with a reverse search?
You're on the right track. The following shows how you can retrieve the last character in a string; you can then check if it's a member of the whitespaceAndNewlineCharacterSet as you suggested.
unichar last = [myString characterAtIndex:[myString length] - 1];
if ([[NSCharacterSet whitespaceAndNewlineCharacterSet] characterIsMember:last]) {
// ...
}
Maybe you can use length on an NSString object to get its length and then use:
- (unichar)characterAtIndex:(NSUInteger)index
with index as length - 1. Now you have the last character which can be compared with [NSCharacter whitespaceAndNewlineCharacterSet].
#implementation NSString (Additions)
- (BOOL)endsInWhitespaceOrNewlineCharacter {
NSUInteger stringLength = [self length];
if (stringLength == 0) {
return NO;
}
unichar lastChar = [self characterAtIndex:stringLength-1];
return [[NSCharacterSet whitespaceAndNewlineCharacterSet] characterIsMember:lastChar];
}
#end