Convert String into special - splitting an NSString - iphone

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

Related

How to get integer values from nsstring Evalution in iPhone?

I have NSString like this #"0,0,0,0,0,0,1,2012-03-08,2012-03-17". I want values separated by comma. I want values before comma and neglect comma.
I am new in iPhone, I know how to do in Java but not getting how to do in Objective-C.
NSString *string = #"0,0,0,0,0,0,1,2012-03-08,2012-03-17";
NSArray *componentArray = [string componentSeperatedByString:#","];
Use the componentsSeparatedByString: method of NSString.
NSString *str = #"0,0,0,0,0,0,1,2012-03-08,2012-03-17";
NSArray *components = [str componentsSeparatedByString:#","];
for (NSString *comp in components)
{
NSLog(#"%#", comp);
}
for (NSString *s in [yourstring componentsSeparatedByString:#","])
{
int thisval = [s intValue];
}

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.

NSString to NSArray

I want to split an NSString into an NSArray. For example, given:
NSString *myString=#"ABCDEF";
I want an NSArray like:
NSArray *myArray={A,B,C,D,E,F};
How to do this with Objective-C and Cocoa?
NSMutableArray *letterArray = [NSMutableArray array];
NSString *letters = #"ABCDEF𝍱क्";
[letters enumerateSubstringsInRange:NSMakeRange(0, [letters length])
options:(NSStringEnumerationByComposedCharacterSequences)
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[letterArray addObject:substring];
}];
for (NSString *i in letterArray){
NSLog(#"%#",i);
}
results in
A
B
C
D
E
F
𝍱
क्
enumerateSubstringsInRange:options:usingBlock: available for iOS 4+ can enumerate a string with different styles. One is called NSStringEnumerationByComposedCharacterSequences, what will enumerate letter by letter but is sensitive to surrogate pairs, base characters plus combining marks, Hangul jamo, and Indic consonant clusters, all referred as Composed Character
Note, that the accepted answer "swallows" 𝍱and breaks क् into क and ्.
Conversion
NSString * string = #"A B C D E F";
NSArray * array = [string componentsSeparatedByString:#" "];
//Notice that in this case I separated the objects by a space because that's the way they are separated in the string
Logging
NSLog(#"%#", array);
This is what the console returned
NSMutableArray *chars = [[NSMutableArray alloc] initWithCapacity:[theString length]];
for (int i=0; i < [theString length]; i++) {
NSString *ichar = [NSString stringWithFormat:#"%C", [theString characterAtIndex:i]];
[chars addObject:ichar];
}
This link contains examples to split a string into a array based on sub strings and also based on strings in a character set. I hope that post may help you.
here is the code snip
NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[myString length]];
for (int i=0; i < [myString length]; i++) {
NSString *ichar = [NSString stringWithFormat:#"%c", [myString characterAtIndex:i]];
[characters addObject:ichar];
}
Without loop you can use this:
NSString *myString = #"ABCDEF";
NSMutableString *tempStr =[[NSMutableString alloc] initWithString:myString];
if([myString length] != 0)
{
NSError *error = NULL;
// declare regular expression object
NSRegularExpression *regex =[NSRegularExpression regularExpressionWithPattern:#"(.)" options:NSMatchingReportCompletion error:&error];
// replace each match with matches character + <space> e.g. 'A' with 'A '
[regex replaceMatchesInString:tempStr options:NSMatchingReportCompletion range:NSMakeRange(0,[myString length]) withTemplate:#"$0 "];
// trim last <space> character
[tempStr replaceCharactersInRange:NSMakeRange([tempStr length] - 1, 1) withString:#""];
// split into array
NSArray * arr = [tempStr componentsSeparatedByString:#" "];
// print
NSLog(#"%#",arr);
}
This solution append space in front of each character with the help of regular expression and uses componentsSeparatedByString with <space> to return an array
Swift 4.2:
String to Array
let list = "Karin, Carrie, David"
let listItems = list.components(separatedBy: ", ")
Output : ["Karin", "Carrie", "David"]
Array to String
let list = ["Karin", "Carrie", "David"]
let listStr = list.joined(separator: ", ")
Output : "Karin, Carrie, David"
In Swift, this becomes very simple.
Swift 3:
myString.characters.map { String($0) }
Swift 4:
myString.map { String($0) }

Build string with variable number of keys and formats

I have an NSDictionary object that contains my data. I am passing in an array of key names and a display format for a string representation of my data.
[self displayMyDataWithTheseKeys:myKeyArray inThisFormat:myFormat];
where, for example,
myKeyArray = [NSArray arrayWithObjects: #"Key1", #"Key2", nil];
myFormat = [NSString stringWithString: #"%# to the %# degree"];
However, myFormat may change and the number of keys in the array may vary as well.
If the number of elements in the array was always 2, this would be trivial. However, how can I handle a variable number of elements?
There isn't really a built-in method for this, but it's relatively easy to parse format strings with NSScanner. Here's a simple example, it only handles %# format specifiers, but as all elements in an NSArray are objects and not primitive types anyway, it shouldn't matter:
NSArray *myKeyArray = [NSArray arrayWithObjects: #"Key1", #"Key2", nil];
NSString *myFormat = [NSString stringWithString: #"%# to the %# degree"];
NSMutableString *result = [NSMutableString string];
NSScanner *scanner = [NSScanner scannerWithString:myFormat];
[scanner setCharactersToBeSkipped:[NSCharacterSet illegalCharacterSet]];
int i = 0;
while (![scanner isAtEnd]) {
BOOL scanned = [scanner scanString:#"%#" intoString:NULL];
if (scanned) {
if (i < [myKeyArray count]) {
[result appendString:[myKeyArray objectAtIndex:i]];
i++;
} else {
//Handle error: Number of format specifiers doesn't
//match number of keys in array...
}
}
NSString *chunk = nil;
[scanner scanUpToString:#"%#" intoString:&chunk];
if (chunk) {
[result appendString:chunk];
}
}
Use: stringByAppendingString
Here's an example on how to use it:
NSString *someString = #"String";
someString = [someString stringByAppendingString:[NSString stringWithFormat:#"%#",variable1]];
someString = [someString stringByAppendingString:[NSString stringWithFormat:#"%#",variable2]];
someString = [someString stringByAppendingString:[NSString stringWithFormat:#"%#",variable3]];
...and so on
If you have an array of keys which you want to put in a string:
NSString *string = #"And the keys are:\n";
for(int i = 0; i < [array count]; i++)
{
NSString *thisKey = (NSString *)[array objectAtIndex:i];
string = [string stringByAppendingString:[NSString stringWithFormat:#"Key number %d is %#",i,thisKey]];
}

how to remove particular words from strings?

I have an NSString *str, having value #"I like Programming and gaming."
I have to remove "I" "like" & "and" from my string so it should look like as "Programming gaming"
How can I do this, any Idea?
NSString *newString = #"I like Programming and gaming.";
NSString *newString1 = [newString stringByReplacingOccurrencesOfString:#"I" withString:#""];
NSString *newString12 = [newString1 stringByReplacingOccurrencesOfString:#"like" withString:#""];
NSString *final = [newString12 stringByReplacingOccurrencesOfString:#"and" withString:#""];
Assigned to wrong string variable edited now it is fine
NSLog(#"%#",final);
output : Programming gaming
NSString * newString = [#"I like Programming and gaming." stringByReplacingOccurrencesOfString:#"I" withString:#""];
newString = [newString stringByReplacingOccurrencesOfString:#"like" withString:#""];
newString = [newString stringByReplacingOccurrencesOfString:#"and" withString:#""];
NSLog(#"%#", newString);
More efficient and maintainable than doing a bunch of stringByReplacing... calls in series:
NSSet* badWords = [NSSet setWithObjects:#"I", #"like", #"and", nil];
NSString* str = #"I like Programming and gaming.";
NSString* result = nil;
NSArray* parts = [str componentsSeparatedByString:#" "];
for (NSString* part in parts) {
if (! [badWords containsObject: part]) {
if (! result) {
//initialize result
result = part;
}
else {
//append to the result
result = [NSString stringWithFormat:#"%# %#", result, part];
}
}
}
It is an old question, but I'd like to show my solution:
NSArray* badWords = #[#"the", #"in", #"and", #"&",#"by"];
NSMutableString* mString = [NSMutableString stringWithString:str];
for (NSString* string in badWords) {
mString = [[mString stringByReplacingOccurrencesOfString:string withString:#""] mutableCopy];
}
return [NSString stringWithString:mString];
Make a mutable copy of your string (or initialize it as NSMutableString) and then use replaceOccurrencesOfString:withString:options:range: to replace a given string with #"" (empty string).