Splitting NSString into two parts (before and after last slash) [duplicate] - ios

This question already has answers here:
Split an NSString to access one particular piece
(7 answers)
Closed 7 years ago.
Is there a better (more concise/efficient/elegant) way than this for splitting a string that contains a slash into two parts: one before, the other after the last slash.
NSRange range = [s rangeOfString: #"/" options: NSBackwardsSearch];
NSAssert(range.location != NSNotFound, nil);
NSString *s1 = [s substringToIndex: range.location];
NSString *s2 = [s substringFromIndex: range.location + 1];

you can use
- componentsSeparatedByString:
eg
NSArray *components = [s componentsSeparatedByString:#"/"];
NSString *s1 = ((![components count])? nil :[components objectAtIndex:0] );
NSString *s2 = ((![components count]>0)? nil :[components objectAtIndex:1] );

Related

How to trim string till first alphabet in a alphanumeric string? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have a alpha numeric string as 24 minutes i want to trim it like 24mplease tell me how can i do this ?
try use code in regex:
NSString *string = #"24 minutes";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"([0-9]+)[^a-zA-Z]*([a-zA-Z]{1}).*" options:NSRegularExpressionCaseInsensitive error:nil];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:#"$1$2"];
NSLog(#"%#", modifiedString);
output:
24m
You can use the componentsSeparatedByString: and substringToIndex: methods of NSString Class, to achieve the result.
NSString *str = #"24 minutes";
NSArray *components = [str componentsSeparatedByString:#" "];
// Validation to prevent array out of index crash (If input is 24)
if ([components count] >= 2)
{
NSString *secondStr = components[1];
// Validation to prevent crash (If input is 24 )
if (secondStr.length)
{
NSString *shortName = [secondStr substringToIndex:1];
str = [NSString stringWithFormat:#"%#%#",components[0],shortName];
}
}
NSLog(#"%#",str);
This example works with the above string, however you need to take care of different type of inputs. It can fail if there is multiple spaces between those values.
NSString *aString = #"24 minutes"; // can be "1 minute" also.
First divide the string into two components:
Divide it with white space, since your string can contain one or more number also like "1 minute", "24 mintutes".
NSArray *array = [aString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
array = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"SELF != ''"]];
NSLog(#"%#",[array objectAtIndex:0]);
Then fetch the first letter of the second component of the string using substringToIndex and finally combine both the strings.
NSString * firstLetter = [[array objectAtIndex:1] substringToIndex:1];
NSString *finalString = [[array objectAtIndex:0] stringByAppendingString:firstLetter];
NSLog(#"%#",finalString);

In objective-c how to get characters after n-th?

I have a number which will be represented as string. It is longer than 4 chars. I need to create new string from 5th till the end for that number.
For example if I have 56789623, I need to have 9623 as a result (5678 | 9623).
How to do that?
P.S. I suppose that this is very simple question, but I don't know how properly ask Google about that.
NSString *str = #"56789623";
NSString *first, *second;
if ([str length] > 4) {
first = [str substringWithRange:NSMakeRange(0, 4)];
second = [str substringWithRange:NSMakeRange(4, [str length] - 4)];
} else {
first = str;
second = nil;
}
Use this Simple functions
- (NSString *)substringFromIndex:(NSUInteger)from;
- (NSString *)substringToIndex:(NSUInteger)to;
- (NSString *)substringWithRange:(NSRange)range;
You can use:
- (NSString *)substringFromIndex:(NSUInteger)anIndex
NSString *number = #"56789623";
NSString *result = [number substringFromIndex:4];
NSLog(#"%#", result);
result contains the string: #"9623"
The keywords you were looking for are: substring and range. There are several ways to use them. Example code split string into 2 equal (if number of characters is even almost equal) substrings:
NSString *str = #"56789623";
NSInteger middleIndex = (NSInteger)(str.length/2);
NSString *strFirstPart = [str substringToIndex:middleIndex];
NSString *strSecondPart = [str substringFromIndex:middleIndex];
NSString *strFirstPart2 = [str substringWithRange:NSMakeRange(0, middleIndex)];
NSString *strSecondPart2 = [str substringWithRange:NSMakeRange(middleIndex, [str length]-middleIndex)];

How to fetch the last word from textfield [duplicate]

This question already has answers here:
Getting the last word of an NSString
(7 answers)
Closed 8 years ago.
I have the following text in the text field
The Taj, Restraint, Renovation, Catch
How to get the Catch word alone from the text field.
NSString *str = #"The Taj, Restraint, Renovation, Catch";
NSString *lastWord = [[str componentsSeparatedByString:#","] lastObject];
Try this
NSString *myString = #"Taj, Restraint, Renovation, Catch" ;
__block NSString *lastWord = nil;
[myString enumerateSubstringsInRange:NSMakeRange(0, myString.length) options:(NSStringEnumerationByWords | NSStringEnumerationReverse) usingBlock:^(NSString *substring, NSRange subrange, NSRange enclosingRange, BOOL *stop) {
lastWord = substring;
*stop = YES;
}];

Extract one word from a two word string

I have a two word string in another view controller containing a user defined first and last name
NSString *userName = ([self hasAttributeWithName:kContractorName] ? [self attributeWithName:kContractorName].value : [self.certificate.contractor.name uppercaseString]);
when retrieving this string in another view controller I want to extract only the first name.
I researched SO on using scanner and found a very helpful answer here: Objective C: How to extract part of a String (e.g. start with '#'), and im almost there.
The problem is I can only seem extract the second name with my variation on the origial code. Im scanning my string up to the space between first and second name, this returns the second name fine. Just need a nudge now on how to set this to extract the first name instead of the second
NSMutableArray *substrings = [NSMutableArray new];
NSScanner *scanner = [NSScanner scannerWithString:userName];
[scanner scanUpToString:#" " intoString:nil]; // Scan all characters before
while(![scanner isAtEnd]) {
NSString *name = nil;
[scanner scanString:#" " intoString:nil]; // Scan the character
if([scanner scanUpToString:#" " intoString:&name]) {
// If the space immediately followed the , this will be skipped
[substrings addObject:name];
}
[scanner scanUpToString:#" " intoString:nil]; // Scan all characters before next
}
Better use NSString's componentsSeparatedByString method:
NSString* firstName = [userName componentsSeparatedByString:#" "][0];
If first and last name are separated with a space you can use:
NSArray *terms = [userName componentsSeparatedByString:#" "];
NSString *firstName = [terms objectAtIndex:0];
You could just split the string into first and last names using componentsSeparatedByString.
NSArray *subStrings = [userName componentsSeparatedByString:#" "];
NSString *firstName = [subStrings objectAtIndex:0];
Sure, you can just split the string by spaces and take the first element, but where’s the fun in that? Try NSLinguisticTagger to actually split this using a Cocoa API:
__block NSString *firstWord = nil;
NSString *question = #"What is the weather in San Francisco?";
NSLinguisticTaggerOptions options = NSLinguisticTaggerOmitWhitespace | NSLinguisticTaggerOmitPunctuation | NSLinguisticTaggerJoinNames;
NSLinguisticTagger *tagger = [[NSLinguisticTagger alloc] initWithTagSchemes: [NSLinguisticTagger availableTagSchemesForLanguage:#"en"] options:options];
tagger.string = question;
[tagger enumerateTagsInRange:NSMakeRange(0, [question length]) scheme:NSLinguisticTagSchemeNameTypeOrLexicalClass options:options usingBlock:^(NSString *tag, NSRange tokenRange, NSRange sentenceRange, BOOL *stop) {
firstWord = [question substringWithRange:tokenRange];
*stop = YES;
}];

Finding first letter in NSString and counting backwards

I'm new to IOS, and was looking for some guidance.
I have a long NSString that I'm parsing out. The beginning may have a few characters of garbage (can be any non-letter character) then 11 digits or spaces, then a single letter (A-Z). I need to get the location of the letter, and get the substring that is 11 characters behind the letter to 1 character behind the letter.
Can anyone give me some guidance on how to do that?
Example: '!!2553072 C'
and I want : '53072 '
You can accomplish this with the regex pattern: (.{11})\b[A-Z]\b
The (.{11}) will grab any 11 characters and the \b[A-Z]\b will look for a single character on a word boundary, meaning it will be surrounded by spaces or at the end of the string. If characters can follow the C in your example then remove the last \b. This can be accomplished in Objective-C like so:
NSError *error;
NSString *example = #"!!2553072 C";
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"(.{11})\\b[A-Z]\\b"
options:NSRegularExpressionCaseInsensitive
error:&error];
if(!regex)
{
//handle error
}
NSTextCheckingResult *match = [regex firstMatchInString:example
options:0
range:NSMakeRange(0, [example length])];
if(match)
{
NSLog(#"match: %#", [example substringWithRange:[match rangeAtIndex:1]]);
}
There may be a more elegant way to do this involving regular expressions or some Objective-C wizardry, but here's a straightforward solution (personally tested).
-(NSString *)getStringContent:(NSString *)input
{
NSString *substr = nil;
NSRange singleLetter = [input rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]];
if(singleLetter.location != NSNotFound)
{
NSInteger startIndex = singleLetter.location - 11;
NSRange substringRange = NSMakeRange(start, 11);
substr = [tester substringWithRange:substringRange];
}
return substr;
}
You can use NSCharacterSets to split up the string, then take the first remaining component (consisting of your garbage and digits) and get a substring of that. For example (not compiled, not tested):
- (NSString *)parseString:(NSString *)myString {
NSCharacterSet *letters = [NSCharacterSet letterCharacterSet];
NSArray *components = [myString componentsSeparatedByCharactersInSet:letters];
assert(components.count > 0);
NSString *prefix = components[0]; // assuming relatively new Xcode
return [prefix substringFromIndex:(prefix.length - 11)];
}
//to get rid of all non-Digits in a NSString
NSString *customerphone = CustomerPhone.text;
int phonelength = [customerphone length];
NSRange customersearchRange = NSMakeRange(0, phonelength);
for (int i =0; i < phonelength;i++)
{
const unichar c = [customerphone characterAtIndex:i];
NSString* onechar = [NSString stringWithCharacters:&c length:1];
if(!isdigit(c))
{
customerphone = [customerphone stringByReplacingOccurrencesOfString:onechar withString:#"*" options:0 range:customersearchRange];
}
}
NSString *PhoneAllNumbers = [customerphone stringByReplacingOccurrencesOfString:#"*" withString:#"" options:0 range:customersearchRange];

Resources