Find difference between two comma separated NSMutableString - ios

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

Related

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

Separate a string into different Array

I have a string coming from server , i want to show some part of string in a view and rest part of string in other view .
Thanks for help.
i want to get the last word of last line of first view. i have searched ,but nothing seems to help me. If any one can suggest me something i would be glad to him/her.
NSString *fromIndex = [_categoryWiseNews.article substringWithRange:NSMakeRange(0, lastWordOfFirstView)];
i have tried with substringWithRange but with this you have to know the lastWordOfFirstView index number for breaking the string into two parts, for which i have no idea.
I really don't know what it is that you're asking lastWordOfFirstView might make sense to you because it is relevant to the thing you are working on. But to us it means nothing.
You can separate a string into words in an array doing this...
NSString *string = #"Hello world, this is a string";
NSArray *array = [string componentsSeparatedByString:#" "];
// array is now... [#"Hello", #"world,", #"this", #"is", #"a", #"string"];
Then you can get the last word from it...
NSString *lastWord = [array lastObject];
Use this to get the last word from a sentence:
NSString *lastWord = [[fullSentenceString componentsSeparatedByString:#" "] lastObject];

stringWithFormat returning newline

I am adding objects to a mutable array by selecting choice(s) from my table view and viewing them in a text field. When I use stringWithFormat, the line of code is automatically adding in characters.
Example: I choose Bob from my table view
Bob
When I do a NSLog, it is actually appearing as
(
Bob
)
But what is appearing in the text field is
( Bob)
Because there is
(\n Bob\n)
Here is the code that I am using to rid of the parentheses and replace commas with semicolons.
// All Names is the mutable array I am adding information in. tableData is another mutable array with set names in them
[AllNames addObject:tableData[0]];
// If I chose the first option
// NSString
ourForces = [NSString stringWithFormat: AllNames[0]];
// NSString
combinedForces = [ourForces stringByReplacingOccurrencesOfString:#"," withString:#";"];
// NSString
twoCombindForces = [combinedForces stringByReplacingOccurrencesOfString:#"(" withString:#""];
// NSString
UltmateCombinedForces = [twoCombindForces stringByReplacingOccurrencesOfString:#")" withString:#""];
//personnel is the text field
personnel.text = UltmateCombinedForces;
Question now is : What is a less messy path to get
( Bob)
to appear as
Bob
in my text field?
Solution update: After the following lines:
// All Names is the mutable array I am adding information in. tableData is another mutable array with set names in them
[AllNames addObject:tableData[0]];
// If I chose the first option
// NSString
ourForces = [NSString stringWithFormat: AllNames[0]];
Include the following line of code:
personnel.text = [AllNames componentsJoinedByString:#";"];
That got rid of the (\n Bob\n) extra characters that were showing up in the field. Thank you all for you help and wisdom. =)
Use componentsJoinedByString: after filling the AllNames array:
personnel.text = [AllNames componentsJoinedByString:#";"];
OK, I think I understand what you're trying to do now.
You have an array of names...
NSArray *names = #[#"Bob", #"Sam", #"Dave"];
And you want a string of all these names...
#"Bob; Sam; Dave"
You seem to be separating them with a semi colon though? ; Is that correct?
You can do this with...
NSString *nameList = [names componentsJoinedByString:#"; "];
But I'm not entirely sure that this is what you're trying to achieve.
In NSLog the output expression
(
Bob
)
represents an array. To get rid of the parentheses and newlines instead of
NSLog(#"%#", AllNames[0]);
write
NSLog(#"%#", AllNames[0][0]);
… and please use variable names starting with a lowercase letter.
You can use NSCharacter Set to remove items you don't want.. The below might offer a less messy solution.
NSString *originalText = #"( Bob) ";
NSMutableCharacterSet *unwantedChars = [NSMutableCharacterSet whitespaceAndNewlineCharacterSet];
[unwantedChars addCharactersInString:#"()"];
NSString *refinedText = [[originalText componentsSeparatedByCharactersInSet:unwantedChars] componentsJoinedByString:#""];

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 do I break in the NSArray with NSString substrings enclosed in quotes

I have a NSSring:
NSString *example = #"'example01','example02','example03','example04'";
How can I make from this line NSArray?
NSString *example = [example stringByReplacingOccurrencesOfString:#"'" withString:#""];
NSArray * exampleArr = [example componentsSeparatedByString:#","];
NSArray *commaSeparatedComponents = [example componentsSeparatedByString:#","];
NSCharacterSet *quotesSet = [NSCharacterSet characterSetWithCharactersInString:#"'"];
for (NSString *component in commaSeparatedComponents) {
NSString *correctlyTrimmedComponent = [component stringByTrimmingCharactersInSet:quotesSet]; // only remove 's at the edges
// ... do something with each component; maybe add to a mutable array ...
}
This has the advantage over the other answer to not remove quotes that exist inside the values, but it doesn't do anything to actually solve quotes escaping that might have been necessary inside the data, and so on. It still misbehaves with some strings, but it misbehaves for fewer cases because it is less flippant about which quotes it removes.
If this is anything above and beyond a string in that exact format, you will probably need a parser for this sort of string that can handle the semantics of how the quotes are escaped, gracefully handles garbage, etc.

Resources