Substring after substring in NSString - iphone

I am new in objective and I'm facing my first problem, and I can not continue my first project.
it's quite simple, I have a NSString :
NSString *myString = #"<font face='Helvetica' size=25 color='#d79198'> Here is some text !</font>";
what I want to do is to get the value of the size "25" which is always 2 char long, so I can calculate my UILabel size.
i know how to detect if there is the substring I am looking for "size=" using :
if ([string rangeOfString:#"bla"].location == NSNotFound)
but I have not found or not understand how to extract the string #"size=XX" and then get the XX as a NSString from *myString
Thank for any help.

NSString *myString = #"<font face='Helvetica' size=25 color='#d79198'> Here is some text !</font>";
NSRange range = [myString rangeOfString:#"size="];
if (range.location != NSNotFound)
{
NSLog(#"Found \"size=\" at %d", range.location);
NSString *sizeString = [myString substringWithRange:NSMakeRange(range.location+5, 2)];
NSLog(#"sizeString: %#", sizeString);
}
This should do the trick. You could also at the end do this: int sizeFont = [sizeString intValue];

NSString *myString = #"<font face='Helvetica' size=25 color='#d79198'> Here is some text !</font>";
if ([myString rangeOfString:#"size"].location != NSNotFound)
{
myString = [myString substringFromIndex:[myString rangeOfString:#"size"].location];
myString = [myString substringToIndex:[myString rangeOfString:#" "].location]; // Now , myString ---> size=25 color='#d79198'> Here is some text !</font>
myString = [myString substringFromIndex:[myString length]-2];// Now, myString ---> size=25
NSLog(#"myString -- %#",myString); // Now, myString ---> 25
}

If you have string like stack:overflow then use it as follow :
NSString *Base=#"stack:overflow"
NSString *one = [[Base componentsSeparatedByString:#":"] objectAtIndex:0];
NSString *two = [[Base componentsSeparatedByString:#":"] objectAtIndex:1];
In this case one = stack and two=overflow

Part of an HTML page? Then use the tool that is designed for the task.

You could calculate the range of the number yourself or use a very simple regular expression to get the substring, something like
(?<=size\=)\d*
This means that you are searching for digits (\d*) that is preceded by "size=" ((?<=size\=))
Which using NSRegularExpression would be
NSError *error = NULL;
NSRegularExpression *regex =
[NSRegularExpression regularExpressionWithPattern:#"(?<=size\\=)\\d*"
options:0
error:&error];
NSTextCheckingResult *match =
[regex firstMatchInString:myString
options:0
range:NSMakeRange(0, [myString length])];
NSString *sizeText = [myString substringWithRange:match.range];
Finally you should convert the text "25" into a number using
NSInteger size = [sizeText integerValue];

Use componentsSeparatedByString: method...
NSString *myString = #"<font face='Helvetica' size=25 color='#d79198'> Here is some text !</font>";
NSString *theSizeString = [[[[myString componentsSeparatedByString:#" "] objectAtIndex:2] componentsSeparatedByString:#"="] objectAtIndex:1];
NSLog(#"The sizestring:%#",theSizeString);
I think it will be helpful to you.

You can get the range of the string #"size=". The range has location and length. So what you need next is to call on the myString the substringWithRange: method. The parameter would be an NSRage starting from the location+length of #"size=" and length of 2.

Related

Find the index of a character in a string

I have a string NSString *Original=#"88) 12-sep-2012"; or Original=#"8) blablabla";
I want to print only the characters before the ")" so how to find the index of the character ")". or how could i do it?
Thanks in advance.
To print the characters before the first right paren, you can do this:
NSString *str = [[yourString componentsSeparatedByString:#")"] objectAtIndex:0];
NSLog(#"%#", str);
// If you need the character index:
NSUInteger index = str.length;
U can find index of the character ")" like this:
NSString *Original=#"88) 12-sep-2012";
NSRange range = [Original rangeOfString:#")"];
if(range.location != NSNotFound)
{
NSString *result = [Original substringWithRange:NSMakeRange(0, range.location)];
}
You can use the following code to see the characters before ")"
// this would split the string into values which would be stored in an array
NSArray *splitStringArray = [yourString componentsSeparatedByString:#")"];
// this would display the characters before the character ")"
NSLog(#"%#", [splitStringArray objectAtIndex:0]);
NSUInteger index = [Original rangeOfString:#")"];
NSString *result = [Original substringWithRange:NSMakeRange(0, index)];
try the below code to get the index of a particular character in a string:-
NSString *string = #"88) 12-sep-2012";
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:#")"];
NSRange range = [string rangeOfCharacterFromSet:charSet];
if (range.location == NSNotFound)
{
// ... oops
}
else {
NSLog(#"---%d", range.location);
// range.location is the index of character )
}
and to get the string before the ) character use this:-
NSString *str = [[string componentsSeparatedByString:#")"] objectAtIndex:0];
Another soluation:
NSString *Original=#"88) 12-sep-2012";
NSRange range = [Original rangeOfString:#")"];
NSString *result = Original;
if (range.location != NSNotFound)
{
result = [Original substringToIndex:range.location];
}
NSLog(#"Result: %#", result);

Convert String into special - splitting an NSString

I have a string like: "mocktail, wine, beer"
How can I convert this into: "mocktail", "wine", "beer"?
the following gives you the desired result:
NSString *_inputString = #"\"mocktail, wine, beer\"";
NSLog(#"input string : %#", _inputString);
NSLog(#"output string : %#", [_inputString stringByReplacingOccurrencesOfString:#", " withString:#"\", \""]);
the result is:
input string : "mocktail, wine, beer"
output string : "mocktail", "wine", "beer"
You need to use:
NSArray * components = [myString componentsSeparatedByString: #", "];
NSString *string = #"mocktail, wine, beer";
//remove whitespaces
NSString *trimmedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//get array of string
NSArray *array = [trimmedString componentsSeparatedByString:#","];
NSMutableArray *newArray = [[NSMutableArray alloc] init];
for (NSString *trimmedString in array) {
NSString *newString = [NSMutableString stringWithFormat:#"'%#'", trimmedString];
[newArray addObject:newString];
}
//merge new strings
NSString *finalString = [NSString stringWithFormat:#"%#", [newArray objectAtIndex:0]];
for (NSInteger i = 1; i < [newArray count]; i++) {
finalString = [NSString stringWithFormat:#"%#, %#", finalString, [newArray objectAtIndex:i]];
}
Without knowing spesifically about iOS or objective-c, I assume you could use a split function.
In almost any higher level programming language there is such a function.
Try:
Objective-C split
This gets you an array of Strings. You can then practically do with those what you want to do, e.g. surrounding them with single quotes and appending them back together. :D

Take part of string in-between symbols?

I would like to be able to take the numbers lying behind the ` symbol and in front of any character that is non-numerical and convert it into a integer.
Ex.
Original String: 2*3*(123`)
Result: 123
Original String: 4`12
Result: 4
Thanks,
Regards.
You can use regular expressions. You can find all the occurrences like this:
NSString *mystring = #"123(12`)456+1093`";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"([0-9]+)`" options:0 error:nil];
NSArray *matches = [regex matchesInString:mystring options:0 range:NSMakeRange(0, mystring.length)];
for (NSTextCheckingResult *match in matches) {
NSLog(#"%#", [mystring substringWithRange:[match rangeAtIndex:1]]);
}
// 12 and 1093
If you only need one occurrence, then replace the for loop with the following:
if (matches.count>0) {
NSTextCheckingResult *match = [matches objectAtIndex:0];
NSLog(#"%#", [mystring substringWithRange:[match rangeAtIndex:1]]);
}
There can be better way to do this, Quickly i could come up with this,
NSString *mystring = #"123(12`)";
NSString *neededString = nil;
NSScanner *scanner =[NSScanner scannerWithString:mystring];
[scanner scanUpToString:#"`" intoString:&neededString];
neededString = [self reverseString:neededString];
NSLog(#"%#",[self reverseString:[NSString stringWithFormat:#"%d",[neededString intValue]]]);
To reverse a string you can see this

How can I get an integer value from NSString in an iPhone application?

NSString * str=[zoneDict objectForKey:#"name"];
NSLog(#"==========string zone::==========%#",str);
// str="(GMT +3:00) Baghdad, Riyadh, Moscow, St. Petersbur";
How can I get the 3:00 value from the above string?
NSString *str = #"(GMT -3:00) Baghdad, Riyadh, Moscow, St. Petersbur";
NSRange endRange = [str rangeOfString:#")"];
NSString *timeString = [str substringWithRange:NSMakeRange(5, endRange.location-5)];
NSRange separatorRange = [timeString rangeOfString:#":"];
NSInteger hourInt = [[timeString substringWithRange:NSMakeRange(0, separatorRange.location)] intValue];
NSLog(#"Hour:%d",hourInt);
Rather than trying to extract the time offset from the string, is there any way you could store actual time zone data in your zoneDict? For example you could store NSTimeZone instances instead.
If all you have is the string, you could use an NSRegularExpression object and extract the relevant information using a regular expression instead.
If you could explain further what you're trying to do then there may be an alternative way to achieve what you want.
I like to use -[NSString componentsSeparatedByString]:
NSString *str = #"(GMT -3:00) Baghdad, Riyadh, Moscow, St. Petersbur";
NSArray *myWords = [myString componentsSeparatedByString:#")"];
NSString *temp1 = [myWords objectAtIndex:0];
if ([temp1 rangeOfString:#"-"].location == NSNotFound) {
NSArray *temp2 = [temp1 componentsSeparatedByString:#"+"];
NSString *temp3 = [temp2 objectAtIndex:1];
NSLog(#"Your String - %#", temp3);
}
else {
NSArray *temp2 = [temp1 componentsSeparatedByString:#"-"];
NSString *temp3 = [temp2 objectAtIndex:1];
NSLog(#"Your String - %#", temp3);
}
Output:
Your String - 3:00
Using regular expressions is the better option in my view (if you are forced to extract the '3' only). The regular expression string would contain something like "\d?" but don't quote me on that, you'll have to look up the exact string. Perhaps someone on here could provide the exact string.

Objective-C: Find consonants in string

I have a string that contains words with consonants and vowels. How can I extract only consonants from the string?
NSString *str = #"consonants.";
Result must be:
cnsnnts
You could make a character set with all the vowels (#"aeiouy")
+ (id)characterSetWithCharactersInString:(NSString *)aString
then use the
- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set
method.
EDIT: This will only remove vowels at the beginning and end of the string as pointed out in the other post, what you could do instead is use
- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
then stick the components back together. You may also need to include capitalized versions of the vowels in the set, and if you want to also deal with accents (à á è è ê ì etc...) you'll probably have to include that also.
Unfortunately stringByTrimmingCharactersInSet wont work as it only trim leading and ending characters, but you could try using a regular expression and substitution like this:
[[NSRegularExpression
regularExpressionWithPattern:#"[^bcdefghjklmnpqrstvwx]"
options:NSRegularExpressionCaseInsensitive
error:NULL]
stringByReplacingMatchesInString:str
options:0
range:NSMakeRange(0, [str length])
withTemplate:#""]
You probably want to tune the regex and options for your needs.
Possible, for sure not-optimal, solution. I'm printing intermediate results for your learning. Take care of memory allocation (I didn't care). Hopefully someone will send you a better solution, but you can copy and paste this for the moment.
NSString *test = #"Try to get all consonants";
NSMutableString *found = [[NSMutableString alloc] init];
NSInteger loc = 0;
NSCharacterSet *consonants = [NSCharacterSet characterSetWithCharactersInString:#"bcdfghjklmnpqrstvwxyz"];
while(loc!=NSNotFound && loc<[test length]) {
NSRange r = [[test lowercaseString] rangeOfCharacterFromSet:consonants options:0 range:NSMakeRange(loc, [test length]-loc)];
if(r.location!=NSNotFound) {
NSString *temp = [test substringWithRange:r];
NSLog(#"Range: %# Temp: %#",NSStringFromRange(r), temp);
[found appendString:temp];
loc=r.location+r.length;
} else {
loc=NSNotFound;
}
}
NSLog(#"Found: %#",found);
Here is a NSString category that does the job:
- (NSString *)consonants
{
NSString *result = [NSString stringWithString:self];
NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:#"aeiou"];
while(1)
{
NSRange range = [result rangeOfCharacterFromSet:characterSet options:NSCaseInsensitiveSearch];
if(range.location == NSNotFound)
break;
result = [result stringByReplacingCharactersInRange:range withString:#""];
}
return result;
}