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

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);

Related

Check values between set range [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have text inputed by my user for example GSM=-73dBm, each time a user enters a piece of text it will always have the same letters and equals sign the only thing that will change is the number and if it is positive or negative. With each range of values the result changes for example -1 to -70 is bad, 0 to 50 is good and 51 to 100 is excellent. The only way i can think of doing this is listed each value the user could enter. Like below.
if ([myTextField.text isEqual:#"GSM=-73dBm"]) {
myTextField.text = #"bad";
} else if {
etc..}
There must be an easier way to do check this.
NSString* target = #"GSM=-73dBm";
NSScanner* sc = [[NSScanner alloc] initWithString:target];
[sc scanUpToString:#"=" intoString:nil];
[sc scanString:#"=" intoString:nil];
NSInteger i;
[sc scanInteger:&i];
Now i is the number -73 and you can just do a couple of tests to see what range it's in.
So you can filter out all non numerical values like this.
NSString *stringToFilter = #"GSM=-73dBm";
NSMutableString *targetString = [NSMutableString string];
//these are characters that you want to keep, so numbers and negative sign
NSCharacterSet *required = [NSCharacterSet characterSetWithCharactersInString:#"-0123456789"];
for(int i = 0; i < [stringToFilter length]; i++)
{
unichar curChar = [stringToFilter characterAtIndex:i];
if([required characterIsMember:curChar])
{
[targetString appendFormat:#"%C", curChar];
}
}
//convert string to int value
int yourNumber = targetString.intValue;
NSLog(#"%d",yourNumber);
This will print "-73".
Then from here you could if else and check if values are contained in a certain range.
You could extract the number with regular expression
NSString *string = #"GSM=-73dBm";
NSString *pattern = #"-?\\d+";
NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:nil error:&error];
if (!error) {
NSRange result = [regex rangeOfFirstMatchInString:string options: nil range: NSMakeRange(0, string.length)];
NSInteger number = [[string substringWithRange:result] integerValue];
NSLog(#"%ld", number);
} else {
NSLog(#"%#", error);
}
The pattern:
-? An optional minus sign, if there could also be a plus sign, use [+-]?
\\d+ One or more numeric characters

Get substring from string variable and save to NSMutableArray [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am new to iOS development and facing some problem. I have a string like this M||100|??|L||150|??|S||50. I want to break the string into chunks and save to array, e.g M 100 is on 1st index, L 150 on second index, S 50 on third index.
NSString *str = #"M||100|??|L||150|??|S||50";
NSString *stringWithoutBars = [str stringByReplacingOccurrencesOfString:#"||" withString:#" "];
NSMutableArray *array = [[NSMutableArray alloc]initWithArray:[stringWithoutBars componentsSeparatedByString:#"|??|"]];
You can get Array from your string using this code
NSString *str = #"M||100|??|L||150|??|S||50";
str = [str stringByReplacingOccurrencesOfString:#"||" withString:#" "];
NSArray *array = [str componentsSeparatedByString:#"|??|"];
this will return your expected result.
let str = "M||100|??|L||150|??|S||50"
let array = str.componentsSeparatedByString("|??|")
print(array)
result :
["M||100", "L||150", "S||50"]
///First replace "||" with " "
NSString *your_str = #"M||100|??|L||150|??|S||50";
your_str = [your_str stringByReplacingOccurrencesOfString:#"||" withString:#" "];
///Get array of string
NSArray *arr = [your_str componentsSeparatedByString:#"|??|"];
NSMutableArray *data_arr = [[NSMutableArray alloc] init];
for(NSString *str in arr)
{
///string to data conversion
NSData *data = [your_str dataUsingEncoding:NSUTF8StringEncoding];
//////// add data to array
[data_arr addObject: data];
}
NSLog(#"data_arr =%#",data_arr);
NSString *str = #"M||100|??|L||150|??|S||50";
NSArray *arrt = [str componentsSeparatedByString:#"|??|"];
NSMutableArray *arr = [[NSMutableArray alloc]init];
for (int i = 0; i <= arrt.count - 1; i++) {
[arr addObject:[[arrt objectAtIndex:i] componentsSeparatedByString:#"||"]];
}

How can I substring in a required format in ios [duplicate]

This question already has answers here:
How do you detect words that start with “#” or “#” within an NSString?
(6 answers)
Closed 7 years ago.
I have a string like this ,
NSString *strTest = #"Hii how are you doing #Ravi , how do u do #Kiran where are you #Varun";
I want a substring from the above string which contains only the words which starts with '#'
i.e I need
NSString *strSubstring = #"Ravi #kiran #varun";
Please help me out how could I achieve this
Separate the string like below :-
NSArray * names = [myString componentsSeparatedByString:#" "];
names array will now contain all the words in the string, now you can iterate over the array and check which of its index contains "#" character.
If you find "#", store that index value in some variable.
you will love implementing this code. I have used a regular expression to perform the job. It will give you the matching strings.
NSString *strTest = #"Hii how are you doing #Ravi , how do u do #Kiran where are you #Varun";
NSError *error;
//&[^;]*;
NSRegularExpression *exp =[NSRegularExpression regularExpressionWithPattern:#"#[^ ]*" options:NSRegularExpressionCaseInsensitive error:&error];
NSArray *s1= [exp matchesInString:strTest options:NSMatchingReportCompletion range:NSMakeRange(0, [strTest length]) ];
[s1 enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSTextCheckingResult *result = obj;
NSString *str = [strTest substringWithRange:result.range];
NSLog(#"str %#",str);
}];

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

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] );

How properly extract substrings from an NSString without hardcoding positions?

I have this string returning:
"Monday thru Friday 8:00 AM - 7:30 PM"
I need to eliminate the mon-fri stuff in order to get this:
"8:00AM - 7:30PM"
And then I need to split it into opening time and closing time in order to determine if its open or not:
"8:00AM" && "7:30PM"
But there are a lot of stores and they have different opening and closing times, so I cant just extract 6 characters from 8 or anything like that.
So far I decided to go this route:
NSRange startRange = [storeTime.text rangeOfString:#"-"];
NSString *openString = [storeTime.text substringWithRange:NSMakeRange(16, startRange.location-17)];
NSString *closeString = [storeTime.text substringWithRange:NSMakeRange(startRange.location+2, storeTime.text.length-(startRange.location+2))];
But it just seems like i could break because of the hardcoded start at 16 and it makes me wonder if it could break anywhere else. Any better ideas on how to achieve this?
You can use NSRegularExpression to grab the two time strings out of a string:
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"\\d{1,2}:\\d{2} (AM|PM)"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSString *str = #"Monday thru Friday 8:00 AM - 7:30 PM";
NSArray *m = [regex matchesInString:str
options:0
range:NSMakeRange(0, str.length)];
If you know the text before the time interval is always in the format <someday> thru <someday>, then you can find the index of the first numerical character (digit), and get a substring from that index.
Then, split the time strings on #" - " using the componentsSeparatedByString: method.
Example:
NSString *s = #"monday thru sunday, 0:00 - 23:59";
NSCharacterSet *digits = [NSCharacterSet decimalDigitCharacterSet];
int idx = [s rangeOfChatacterFromSet:digits].location;
NSString *timeStr = [s substringFromIndex:idx];
NSArray *timeStrings = [timeStr componentsSeparatedByString:#" - "];
How about first go by replacing occurrences of some strings.
So use the [string stringByReplacingOccurrencesOfString:#"Monday" withString: #""];
remove all the days and probably the "thru" string.
Then you're left with the hours. Don't forget to watch for space characters.
Hope this helps.

Resources