Display string from Nsarray only if it contains - ios

I am using the following query to check if the strings within a NSArray contain a certain word.
I am struggling to then break it down to display only the string that has the rangeOfString word.
As you can see it currently displays all the results if the NSArray contains the word. How would I single it down further to display only the specific string that contains the "BOLDME" ?
// change this line only for the concatenation
NSString * resultConditions = [legislationArray componentsJoinedByString:#"\n"];
NSString *word = #"BOLDME";
//if string contains
if ([resultConditions rangeOfString:word].location != NSNotFound) {
cell.dynamicTextView.text = resultConditions;
}

Not only will this get you directly to each instance within the array that contains the text you're searching for, but it will also perform significantly better than the code in the question.
for (NSString *testWord in legislationArray) {
if ([testWord rangeOfString:#"BOLDME"].location != NSNotFound) {
// testWord contains "BOLDME"
cell.dynamicTextView.text =
[cell.dynamicTextView.text stringByAppendingString:testWord];
}
}
As written, this will append the found string to whatever text is already in the text view. It may be that you only want one word in the text view. If this is the case, then you should break; as soon as you find the first one.

You can iterate over NSArray and check each string if it contains specific word:
for(NSString *value in array) {
if([value rangeOfString:word] != NSNotFound) {
/* we have found that string*/
}
}

Related

Matching Strings In Array with an other Array from NsUserDefaults

Array From Defaults
NSMutableArray* saveSelectedPlaces;
NSArray* titleArray = #[#"Akshardham",
#"Charminar",
#"Golden Temple",
#"Indian Gate",
#"Kedartnath Temple",
#"Ladakh",
#"Manasasarovar",
#"Mumbai",
#"Ooty",
#"Tajmahal",
#"Thar Desert",];
Title = [titleArray mutableCopy];
My logic to compare strings
for (NSString* currentString in saveSelectedPlaces) {
if (detailcell.DetailTableCellTitle.text == currentString){
detailcell.favouriteButton.selected = YES;
[detailcell.favouriteButton setBackgroundImage:[UIImage imageNamed:#"HeartSelectedSmall"] forState:UIControlStateNormal];
}
}
I have a array of titles saved in defaults , i want to compare those strings with an other array " Title . Then if it matches i want to highlight the images.
Simply, am trying to favoriting a cell.
Please, HELP ME
Thanks
Try this:
Replace if (detailcell.DetailTableCellTitle.text == currentString) with if ([detailcell.DetailTableCellTitle.text isEqualToString: currentString])
The == is simply compares the pointers, which will usually be different even if their contents are the same. The isEqualToString method compares their contents.
More Simple way : You can check if an NSArray contains an object with containsObject.
BOOL contains = [saveSelectedPlaces containsObject: detailcell.DetailTableCellTitle.text];
if (contains)
{
\\ add your code
}

Need to get NSRanges of multiple # symbols and the text that follows them in UILabel's text

I have a UILabel that contains text like this:
"Hi, my name is John Smith. Here is my twitter handle #johnsmith and I work for this company #somerandomcompany. Thanks for watching!"
I need to find the ranges for all of the # symbols and whatever text comes right after them until a space appears, so that I can then bold both the symbol and any text that comes after it until a space appears:
"Hi, my name is John Smith. Here is my twitter handle #johnsmith and I work for this company #somerandomcompany. Thanks for watching!"
I am familiar with using rangeOfString but I have never had to handle multiple ranges like this. I need these NSRanges so that I can pass them into a UILabel category that will bold the appropriate text.
Any help is greatly appreciated.
One way like this :
NSString *strText = #"Hi, my name is John Smith. Here is my twitter handle #johnsmith. Thanks for watching! #somerandomcompany looks good";
//array to store range
NSMutableArray *arrRanges = [NSMutableArray array];
//seperate `#` containing strings
NSArray *arrFoundText = [strText componentsSeparatedByString:#"#"];
//iterate
for(int i=0; i<[arrFoundText count];i++)
{
//leave first substring as it doesnot contain `#` after string
if (i==0) {
continue;
}
//get sub string
NSString *subStr = arrFoundText[i];
//get range for space
NSRange rangeSub = [subStr rangeOfString:#" "];
if (rangeSub.location != NSNotFound)
{
//get string with upto space range
NSString *findBoldText = [subStr substringToIndex:rangeSub.location];
NSLog(#"%#",findBoldText);
//create range for bold text
NSRange boldRange = [strText rangeOfString:findBoldText];
boldRange.location -= 1;
//add to array
[arrRanges addObject:NSStringFromRange(boldRange)];
}
}
NSLog(#"Ranges : %#",arrRanges);

Check whether the NSArray object at index is of kind NSString Or NSNumber

This is my NSArray :
(
"tag_name",
3,
"mp4_url",
4,
0,
"back_tag",
5,
1,
"part_id",
"related_list",
2
)
I need to put all the numerical values in some another array.
I used the following code to check whether the value fetched from the array was a numeric or a string, but it didn't work. Every time i get the value from an array as NSString.
for (int i=0; i<arr.count; i++) {
id obj=[arr objectAtIndex:i];
if ([obj isKindOfClass:[NSString class]])
{
// It's an NSString, do something with it...
NSLog(#"its string");
}else{
// It's an Numerical value, do something with it...
NSLog(#"its integer value");
}
}
I know that array stores only kind of objects in it, so while fetching i'm getting the value as NSString(i.e object). But is there anyway to check whether the value stored was a numeric value.
Please can anyone help me..
Thanks
You can't just turn an NSString into an NSNumber but there are ways that you can try to get he numeric value out of them.
This is one option but you could also have a look at NSNumberFormatter.
If all of the numbers are integers then you could do something like this...
// always use fast enumeration
for (NSString *string in arr) {
NSInteger integer = [string integerValue];
// have to check explicitly for 0 as a non-numeric would return 0 above
if ([string isEqualToString:#"0"]
|| integer != 0) {
// it is an integer numeric string
} else {
// it is a string
}
}

How to filter a string after a particular character in iOS? [duplicate]

This question already has answers here:
Split an NSString to access one particular piece
(7 answers)
Closed 9 years ago.
I want to filter string after character '='. For eg if 8+9=17 My output should be 17. I can filter character before '=' using NSScanner, how to do its reverse??? I need a efficient way to do this without using componentsSeparatedByString or creating an array
Everyone seems to like to use componentsSeparatedByString but it is quite inefficient when you just want one part of a string.
Try this:
NSString *str = #"8+9=17";
NSRange equalRange = [str rangeOfString:#"=" options:NSBackwardsSearch];
if (equalRange.location != NSNotFound) {
NSString *result = [str substringFromIndex:equalRange.location + equalRange.length];
NSLog(#"The result = %#", result);
} else {
NSLog(#"There is no = in the string");
}
Update:
Note - for this specific example, the difference in efficiencies is negligible if it is only being done once.
But in general, using componentsSeparatedByString: is going to scan the entire string looking for every occurrence of the delimiter. It then creates an array with all of the substrings. This is great when you need most of those substrings.
When you only need one part of a larger string, this is very wasteful. There is no need to scan the entire string. There is no need to create an array. There is no need to get all of the other substrings.
NSArray * array = [string componentsSeparatedByString:#"="];
if (array)
{
NSString * desiredString = (NSString *)[array lastObject]; //or whichever the index
}
else
{
NSLog(#""); //report error - = not found. Of array could somehow be not created.
}
NOTE:
Though this is very popular splitting solution, it is only worth trying whenever every substring separated by separator string is required. rmaddy's answer suggest better mechanism whenever the need is only to get small part of the string. Use that instead of this approach whenever only small part of the string is required.
Try to use this one
NSArray *arr = [string componentsSeparatedByString:#"="];
if (arr.count > 0)
{
NSString * firstString = [arr objectAtIndex:0];
NSString * secondString = [arr objectAtIndex:1];
NSLog(#"First String %#",firstString);
NSLog(#"Second String %#",secondString);
}
Output
First String 8+9
Second String 17
Use this:
NSString *a =#"4+6=10";
NSLog(#"%#",[a componentsSeparatedByString:#"="])
;
Log: Practice[7582:11303] (
"4+6",
10
)

How can I access one value among some values

{
"id"=12
"genres_en" = "thriller,movies,action";
}
{
"id"=13
"genres_en" = "thriller,horror";
}
Hi everyone ,
I have one json like this..I mean i have one content and all movie has their genre ..And i need to do one categorization ..For example I need to check which genre of movie is horror..Or which one is thriller..I m getting all value like this:
--> "horror,movies"
But how can i do the controllation to check whether the genre of this movie includes horror or not..??what is your suggesstion?
Thank you
You could use componentsSeparatedByString
NSDictionary *dic = PARSE The JSON;
NSString *values = [dic objectForKey:"genres_en"];
NSString *firstValue = [[values componentsSeparatedByString:","] objectAtIndex:0];
I don't have Xcode nearby, so the following code may contain an error(or two :) ).
Try it like that:
NSDictionary *yourDict = //your parsed json
NSString *genres = [yourDict objectForKey:#"genres_en"];
if ([genres rangeOfString:#"horror"].location != NSNotFound) {
return YES;
} else {
return NO;
}
Hope it helps
for(int j=0;j< GenresArray.count; j++)
{
NSString *value=[[genre componentsSeparatedByString: #","]objectAtIndex:j];
if([value isEqualToString:#"movies"])
{
[genreMovies addObject:value];
}
}
Thank you for your help guys ..Now i have my result:)
You can try to check if the string contains the substring you want . Like this:
NSString *typesString = [dic objectForKey:"genres_en"];
NSRange range = [typesString rangeOfString:#"horror"];
if(range.location != NSNotFound)
{
//it contains the substring "horror"
}
Or , the better way would be to get the array of types.
NSArray *types = [[typesString componentsSeparatedByString:","];
Now you can store this array for each entry and whenever you want to check if it belongs to a certain gender , just loop through the types array ( of each entry ) and compare the strings.
Hope this helps.
Cheers!

Resources