Remove string after the hyphen - ios

I have multiple strings written at the same way:
Name-372198
Another-9849204
Something-3439483
I want to split the string into two parts: first one before the hyphen and the other after the hyphen.
I'm stuck with Objective-c Regular Expression!

Not sure why you're using a regular expression. What's wrong with:
NSString *theString = #"Name-372198";
NSArray *stringComponents = [theString componentsSeparatedByString:#"-"];
The stringComponents array will hold: { #"Name", #"372198" }
Code not tested but should work.

If you are sure there is only one - you might want to look at
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/#//apple_ref/occ/instm/NSString/rangeOfString:options:

No need of a regular expression in this case.
This would do fine
NSArray *stringParts=[yourString componentsSeparatedByString:#"-"];
NSString *part1=stringParts[0];
// has the part before the hyphen
NSString *part2=stringParts[1];
// has the part after the hyphen

Related

stringByReplacingOcurrencesOfString with special character objective c

I am trying to replace instances of 's with s or alternatively instances of s with 's. However, the result of the code below is an empty string. What could I be doing wrong?
NSString *myStr = #"Eat at Joe's";
NSString *newStr = [myStr stringByReplacingOccurrencesOfString:#"\'s" withString:#"s"];
//edited as per Vadian
NSLog(#"newStr:%#",newStr); //logs as newStr:
You forgot the placeholder
NSLog(#"newStr: %#", newStr);
Don't you get the warning
Data argument not used by format string

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

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