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

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
)

Related

Find difference between two comma separated NSMutableString

Suppose I have two NSMutableString like this:-
String 1 ----- {aaa,bss,cdd,dff,eee,fgh}
String 2 ----- {aaa,bss,cdd}
How can we find the the difference between String 1 & String 2 in an NSArray:-
Like this:- { dff,eee,fgh }
As mentioned in duplicate question it is different.
Put both these strings in two different NSMutableSets and then subtract 2nd from 1st.
You will have your result.
NSString* str1 = #"aaa,bss,cdd,dff,eee,fgh";
NSString* str2 = #"aaa,bss,cdd";
NSMutableSet *set1 = [NSMutableSet setWithArray:[str1 componentsSeparatedByString:#","]];
NSMutableSet *set2 = [NSMutableSet setWithArray:[str2 componentsSeparatedByString:#","]];
[set1 minusSet:set2];
NSLog(#"result %#",[set1 allObjects]);
Try with NSMutableArray to remove same objects.
For Eg.
NSString *s1 = #"aaa,bss,cdd,dff,eee,fgh";
NSString *s2 = #"aaa,bss,cdd";
NSArray *arr1 = [s1 componentsSeparatedByString:#","];
NSArray *arr2 = [s2 componentsSeparatedByString:#","];
NSMutableArray *resArray = [NSMutableArray arrayWithArray:arr1];
[resArray removeObjectsInArray:arr2];
NSString *res = [resArray componentsJoinedByString:#","];
NSLog(#"Result :: %#", res);
Hopefully, it'll help you.
Thanks.
First part of the problem is to separate each string into substrings separated by the commas.
To create the substrings you can use
[string substringFromIndex:index] - to get an NSString from that index foward
[string substringToIndex:index] - to get an NSString from the begining to that index
Or you could combine it into
[string substringWithRange:NSMakeRange(fisrtIndex, secondIndex)] - to get a strin from the first index to the second index
Those are the basic operations. But there are a lot more in this case you could use specifically:
[string componentsSeparatedByString:#","] to get an NSArray with all the substrings. That would have the problem of the '{' and '}' appearing in the first and last component. This can be solved in many ways:
by first trimming the string using the substring methods already explained
by using another method altogether
[string componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:#",{"]] The problem with this method is, because your strings start/end with one of the separators you would get the first/last component an empty string. You can just remove it from the array or ignore it or choose the other method, your choice.
Now that you know how to get the substrings all you need to know is how to compare the two. There are literally many ways to do this. I am just going to name a few. Of course each solution has its own advantages and disadvantages and code complexity.
1 - comparing each substring one by one the the other using isEqualToString:
2 - comparing each substring from one of the original strings with the full second original string by using [string2 rangeOfString:substring].location != NSNotFound
3 - if you have iOS 8 or OS X Yosemite you can use [string2 containsString:substring]
4 - You can transform the arrays of substrings into sets and then compare them as Ankit Srivastava suggested
5 - You can use the removeObjectsInArray to get the substrings that are not common between the two and then use that newly created array to removeObjectsInArray to the original and have just the common...
Really the possibilities are almost endless

Using componentsSeparatedByString with more than one separator string?

I have a string that I need to separate into an array of words. I was using NSArray *words = [cleanText componentsSeparatedByString:#" "]; which worked fine, until I ran into the end of a paragraph resulting in the component "end.\n\nStart".
Is there a way to separate the string into components using " " as well as "\n\n" character? Or is there more correct way to solve this?
You are describing splitting a string using a regular expression such as "\s". If you look at e.g. https://github.com/bendytree/Objective-C-RegEx-Categories/blob/master/RegExCategories.m you can obtain code for splitting on a regular expression match.
Alternatively you can split on a character set by calling componentsSeparatedByCharactersInSet: and use whitespaceAndNewlineCharacterSet.
You can split on the whitespaceAndNewlineCharacterSet. You will get empty “words” when cleanText has more than one split character in a row, and you probably want to filter those out.
NSArray *words = [#"" componentsSeparatedByCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
words = [words filteredArrayUsingPredicate:
[NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary *_) {
return [object length] > 0;
}]];

present NSString as a line of elements

I have an NSString that hold data (actually that could be presented an NSArray). and i want to output that on a label.
In NSLog my NSString output is:
(
"cristian_camino",
"daddu_02",
"_ukendt_babe_",
"imurtaza.zoeb"
)
What i want is, to present it like :"cristian_camino","daddu_02","_ukendt_babe_","imurtaza.zoeb"
In a single line.
I could accomplish that turning string to an array and do following: arrayObjectAtIndex.0, arrayObjectAtIndex.1, arrayObjectAtIndex.2, arrayObjectAtIndex.3.
But thats look not good, and that objects may be nil, so i prefer NSString to hold data.
So, how could i write it in a single lane?
UPDATE:
There is the method i want to use to set text for UILabel:
-(void)setLikeLabelText:(UILabel*)label{
//Likes
NSString* likersCount = [self.photosDictionary valueForKeyPath:#"likes.count"];
NSString* likersRecent = [self.photosDictionary valueForKeyPath:#"likes.data.username"];
NSString *textString = [NSString stringWithFormat:#"%# - amount of people like it, recent "likes": %#", likersCount, likersRecent];
label.text = textString;
NSLog(#"text String is %#", textString);
}
valueForKeyPath: returns an NSArray, not an NSString. Whilst you've declared likersCount and likersRecent as instances of NSString, they're actually both arrays of values. You should be able to do something like the following to construct a string:
NSArray* likersRecent = [self.photosDictionary valueForKeyPath:#"likes.data.username"];
NSString *joined = [likersRecent componentsJoinedByString:#"\", \""];
NSString *result = [NSString stringWithFormat:#"\"%#\"", joined];
NSLog(#"Result: %#", result);
componentsJoinedByString: will join the elements of the array with ", ", and then the stringWithFormat call will add a " at the beginning and end.
The statement is incorrect, the internal quote marks (" that you want to display) need to be escaped:
NSString *textString = [NSString stringWithFormat:#"%# - amount of people like it, recent \"likes\": %#", likersCount, likersRecent];
If somebody curious how i fix it, there it is:
for (int i =0; i < [likersRecent count]; i++){
stringOfLikers = [stringOfLikers stringByAppendingString:[NSString stringWithFormat:#" %#", [likersRecent objectAtIndex:i]]];
}
Not using commas or dots though.

Display string from Nsarray only if it contains

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*/
}
}

Obj-c Turning long string into multidimensional array

I have a long NSString, something like "t00010000t00020000t00030000" and so on. I need to split that up into each "t0001000".
I'm using...
NSArray *tileData = [[GameP objectForKey:#"map"] componentsSeparatedByString:#"t"];
And it splits it up, but the "t" is missing, which I need (although I think I could append it back on). The other way I guess would be to split it up by counting 8 char's, although not sure how to do that.
But ideally I need it split into a [][] type array so I can get to each bit with something like...
NSString tile = [[tileData objectAtIndex:i] objectAtIndex:j]];
I'm new to obj-c so thanks for any help.
If they're not strictly the t characters that separate the sections, i. e. the parts are always 8 characters long, then it's very easy to do it:
NSString *string = #"t00010000t00020000t00030000";
NSMutableArray *arr = [NSMutableArray array];
int i;
for (i = 0; i < string.length; i += 8) {
[arr addObject:[string substringWithRange:NSMakeRange(i, 8)]];
}
and here arr will contain the 8-character substrings.
Edit: so let me also provide yet another solution for the multidimensional one. Of course #KevinH's solution with the characters is very elegant, but if you need an NSString and you don't mind implementing another method, it's fairly easy to add something like this:
#implementation NSString (EightCarAdditions)
- (NSString *)charAsStringInSection:(NSInteger)section index:(NSInteger)index
{
return [self substringWithRange:NSMakeRange(section * 8 + index, 1)];
}
- (unichar)charInSection:(NSInteger)section index:(NSInteger)index
{
return [self characterAtIndex:section * 8 + index];
}
#end
(Beware that characterAtIndex returns a unichar and not a char - be prepared for more than 1 byte-wide UTF-(8, 16, 32) stuff.) You can then call these methods on an NSString itself, so it's very convenient:
unichar ch = [string charInSection:1 index:3];
H2CO3's answer is spot-on for the first part. For the second (the multi-dimensional array), if I understand what you want, you don't need another array for the individual characters. For each NSString in the array, you can access each character by calling characterAtIndex. So, extending the example above:
for (NSString *item in arr) {
NSLog(#"The fifth character of this string is: %C", [item characterAtIndex:4]);
}
And if you're looking to chain these together, as in your example, you can do that too:
NSLog(#"The fifth character of the fourth string is: %C",
[[arr objectAtIndex:3] characterAtIndex:4]);

Resources