Format a NSMutableArray object to a string - ios

array is a NSMutableArray. I am adding some string objects to it.
[array addObject:#"MM-19"];
[array addObject:#"MM-49"];
[array addObject:#"MM-165"];
[array addObject:#"MM-163"];
Now, I need to write a method that will return me a NSString in the following format :
19-49-165-163
How can this be done ?

Here is your solution,
NSString *dashSeperatedString = [array componentsJoinedByString:#"-"] ;
dashSeperatedString = [dashSeperatedString stringByReplacingOccurrencesOfString:#"MM-" withString:#""] ;
NSLog(#"Output : %#", dashSeperatedString);

Try this code will help,
NSString *finalString = #"" ;
for (NSString *strvalue in array)
{
NSArray *temp= [strvalue componentsSeparatedByString:#"-"];
if ([strvalue isEqualToString:array.lastObject])
{
finalString= [finalString stringByAppendingString:temp.lastObject];
}
else
{
finalString= [finalString stringByAppendingString:[NSString stringWithFormat:#"%#-",temp.lastObject]];
}
}
NSLog(#"%#",finalString);

Another alternative could be:
NSString *combinedStuff = [array componentsJoinedByString:#""];
combinedStuff = [combinedStuff stringByReplacingOccurrencesOfString:#"MM" withString:#""];
if ([combinedStuff hasPrefix:#"-"])
{
combinedStuff = [combinedStuff substringFromIndex:1];
}

Swift 2.0:
let mutableArray = NSMutableArray()
mutableArray.addObject("MM-19")
mutableArray.addObject("MM-49")
mutableArray.addObject("MM-165")
mutableArray.addObject("MM-163")
var finalString = String()
finalString = ""
for stringValue in mutableArray {
let temp: [AnyObject] = stringValue.componentsSeparatedByString("-")
finalString = finalString.stringByAppendingString(String(temp.last)+"-")
}
print("Final String: \(finalString)")
OR
var finalSeperatedString: String = mutableArray.componentsJoinedByString("-")
finalSeperatedString = finalSeperatedString.stringByReplacingOccurrencesOfString("MM-", withString: "")
print("Output String: \(finalSeperatedString)")
}

Related

Transform punctuations form half width to full width

I have a sentence below:
我今天去买菜,买了一个西瓜,花了1.2元,买了一个土豆,花了3.78元。还买了一个无花果,花了45.89,怎么办呢?好贵呀!贵的我不知道再买什么了。
The punctuations in it are half width. How to change them to fullwidth, like the following:
我今天去买菜,买了一个西瓜,花了1.2元,买了一个土豆,花了3.78元。还买了一个无花果,花了45.89,怎么办呢?好贵呀!贵的我不知道再买什么了。
Some punctuations to consider (not exhaustive):
, to ,
? to ?
! to !
"" to “”
; to ;
First, define the CharacterSet from which you want to transform your characters. So if you want only punctuation, the set could be CharacterSet.punctuationCharacters or CharacterSet.alphanumerics.inverted.
Then map each character from this set to its HalfwidthFullwidth transformation.
Swift 3 and 4
extension String {
func transformingHalfwidthFullwidth(from aSet: CharacterSet) -> String {
return String(characters.map {
if String($0).rangeOfCharacter(from: aSet) != nil {
let string = NSMutableString(string: String($0))
CFStringTransform(string, nil, kCFStringTransformFullwidthHalfwidth, true)
return String(string).characters.first!
} else {
return $0
}
})
}
}
Usage
let string = ",?!\"\";abc012図書館 助け 足場が痛い 多くの涙"
let result = string.transformingHalfwidthFullwidth(from: CharacterSet.alphanumerics.inverted)
// it prints: ,?!"";abc012図書館 助け 足場が痛い 多くの涙
print(result)
Objective-C
#implementation NSString (HalfwidthFullwidth)
- (NSString *)transformingHalfwidthFullwidth:(nonnull NSCharacterSet *)aSet {
NSUInteger len = self.length;
unichar buffer[len + 1];
[self getCharacters:buffer range:NSMakeRange(0, len)];
for (int i = 0; i < len; i++) {
unichar c = buffer[i];
NSMutableString *s = [[NSMutableString alloc] initWithCharacters:&c length:1];
NSRange r = [s rangeOfCharacterFromSet:aSet];
if (r.location != NSNotFound) {
CFStringTransform((CFMutableStringRef)s, nil, kCFStringTransformFullwidthHalfwidth, true);
[s getCharacters:buffer + i range:NSMakeRange(0, 1)];
}
}
return [NSString stringWithCharacters:buffer length:len];
}
#end
Usage
NSString *string = #",?!\"\";abc012図書館 助け 足場が痛い 多くの涙";
NSString *result = [string transformingHalfwidthFullwidth:NSCharacterSet.alphanumericCharacterSet.invertedSet];
// it prints: ,?!"";abc012図書館 助け 足場が痛い 多くの涙
NSLog(result);
you can use CFStringTransform like :
Objective C :
NSString *string = #" ? \"\"!我今天去买菜,买了一个西瓜,花了1.2元,买了一个土豆,花了3.78元。还买了一个无花果,花了45.89,怎么办呢?好贵呀!贵的我不知道再买什么了";
NSMutableString *convertedString = [string mutableCopy];
CFStringTransform((CFMutableStringRef)convertedString, NULL, kCFStringTransformFullwidthHalfwidth, true);
NSLog(#"%#",convertedString);
Swift 3.0 :
let string = NSMutableString( string: " ? \"\"!我今天去买菜,买了一个西瓜,花了1.2元,买了一个土豆,花了3.78元。还买了一个无花果,花了45.89,怎么办呢?好贵呀!贵的我不知道再买什么了" )
CFStringTransform( string, nil, kCFStringTransformFullwidthHalfwidth, true )
print(string)

How to convert string to array in iOS?

NSString *strdetails = [NSString stringWithFormat:#"%#",[[products objectAtIndex:i] valueForKey:#"details"]];
NSLog(#"%#",strdetails);
When I add on array but it's convert to previous data. But I want array not string.
Here is your code:
NSString *strdetails = [NSString stringWithFormat:#"%#",[[products objectAtIndex:i] valueForKey:#"details"]];
NSLog(#"%#",strdetails);
I update this code here:
NSData *objectData = [strdetails dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
// Here you are getting dictionary, Now from this you will get array in this way
// Print this dict
NSLog(#"dict details = %#",dict);
NSArray * arrV = dict[#"variants"];
// check your array
NSString *str=#"Hi,I LOVE IOS";
NSArray *arr = [str componentsSeparatedByString:#","];
NSString *strSecond = [arr objectAtIndex:1];
NSMutableArray *arrIOS = [strSecond componentsSeparatedByString:#" "];
NSString *strI = [arrIOS objectAtIndex:0];
NSString *strLOVE = [arrIOS objectAtIndex:1];
NSString *strIOS = [arrIOS objectAtIndex:2];
[arr removeObjectAtIndex:1];
[arr addObject:#","];
[arr addObject:strI];
[arr addObject:strLOVE];
[arr addObject:strIOS];
I guess you are converting jsonString into Array I am using below function to convert my jsonString.
ViewController
public class func JSONParseArray(jsonString: NSString) -> [AnyObject]?{
if let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding){
if let array = (try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))) as? [AnyObject] {
return array
}
}
return nil
}
If You Want Specific value from Array:
NSArray *outputArray = [array valueForKey:#"YourKey"];

Remove particular String from NSArray not Object

I am new in IOS development.I am getting phone numbers in NSArray and this is something like this.
9429564999,
9428889239,
7878817072,
"+919408524477",
9909951666,
9879824567,
"+91 8469-727523",
"94-28-037780",
"+918460814614",
55246,
"8866-030880",
"95-37-223347",
"+919574777070",
"+917405750526",
Now i want to remove - and +91 from NSArray List not whole object.How to do this Please someone help
for (NSString *number in arrayName) {
number = [number stringByReplacingOccurrencesOfString:#"+91"
withString:#""] mutableCopy];
number = [number stringByReplacingOccurrencesOfString:#"-"
withString:#""] mutableCopy];
[arrayNameNew addObject:number];
}
Try like this :)
Happy Coding.
for (NSString *phoneNum in phoneNumArray) {
phoneNum = [phoneNum stringByReplacingOccurrencesOfString:#"+91" withString:#""];
phoneNum = [phoneNum stringByReplacingOccurrencesOfString:#"-" withString:#""];
}
NSArray *phoneNoList = [[NSArray alloc]initWithObjects:#"9429564999",#"9428889239",#"7878817072",#"+919408524477",#"9909951666",#"9879824567", #"+91 8469-727523",#"94-28-037780",#"+918460814614",#"55246",#"8866-030880",#"95-37-223347",#"+919574777070", #"+917405750526", nil];
NSMutableArray *noArr = [[NSMutableArray alloc]init];
for (NSString *no in phoneNoList) {
NSString *temp1 = [[no componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
componentsJoinedByString:#""];
if (temp1.length > 10) {
NSString *temp=[temp1 substringFromIndex:2];
[noArr addObject:temp];
}
else
[noArr addObject:temp1];
}
NSLog(#"Arr Data : %#",noArr);
Try this, definitely helps to you.
Try this
for (NSString *str in arrayNumbers) {
NSString *stringWithoutNineOne = [str stringByReplacingOccurrencesOfString:#"+91" withString:#""];
NSString *stringWithoutSpace = [stringWithoutNineOne stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *stringWithoutdash = [stringWithoutSpace stringByReplacingOccurrencesOfString:#"-" withString:#""];
[refinedArr addObject:stringWithoutdash];
}
Remove special characters from array.
for (NSString *strPhoneNo in arrayPhoneNo) {
[self removeSpecialCharacter:strPhoneNo];
}
and
-(NSString*)removeSpecialCharacter:(NSString*)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"+91" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
// remove extra special charecter if needed.
//mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
//mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
//mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
return mobileNumber;
}
if NSArray not update then use NSMutableArray insted of NSArray.
You can also try this....
Getting the last 10 digits of your given phone numbers.....if your requirement is fixed then try this single line code
for (NSString *string in arrayNumbers) {
NSString *trimmedString=[string substringFromIndex:MAX((int)[string length]-10, 0)];
[newArray addobject:trimmedString]
}

Get NSString as NSArray from NSDictionary

I've the following data in NSDictionary for an object field_names that has below value.
{dBur0z9,nr8r0,R0ru,jrurw,qB5rz9ry},{gr2,Z5uzr,Rwxyr5z0Ar5},^~gr2~cry69v~br9rtyz~Z03r4rsru^~Z5uzr~Uvy3z~dB4srz^5B33,(),9ruI,evD3rsv3,,HLK,evDsBAA65,evDtyvt2s6E,5B33,5B33,5B33,5B33,{6ww},SRiTfUV,5B33,5B33,5B33,5B33
I'm trying to get it as NSArray. I tried
`NSArray *array = [dictionary objectForKey:#"field_name"];
But that returns an NSString not an NSArray. Then I tried to replace { } with [ ] and appended [ ] to make it json array,
NSString *s =[[dictionary objectForKey:#"field_names"] stringByReplacingOccurrencesOfString:#"{" withString:#"["];
s = [s stringByReplacingOccurrencesOfString:#"}" withString:#"]"];
s= [NSString stringWithFormat:#"[%#]",s];
NSDictionary *temp = #{#"array":s };
NSLog(#"%#", [temp objectForKey:#"array"]);
But still I'm getting it as NSString
[[dBur0z9,nr8r0,R0ru,jrurw,qB5rz9ry],[gr2,Z5uzr,Rwxyr5z0Ar5],^~gr2~cry69v~br9rtyz~Z03r4rsru^~Z5uzr~Uvy3z~dB4srz^5B33,(),9ruI,evD3rsv3,,HLK,evDsBAA65,evDtyvt2s6E,5B33,5B33,5B33,5B33,[6ww],SRiTfUV,5B33,5B33,5B33,5B33]
Please help me getting it NSArray!
You're getting it as a string because it is in fact string. I feel like you're trying to parse it as a JSON string??
If so, you first need to have that string in a valid JSON format. Here's an example JSON
{
   "AnArray": [
"string 1",
      "string 2",
      "string 3"
   ]
}
(without the line breaks of course I just added them for readability)
Once you have it as a valid JSON formatted string, you can do this
NSError *error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData: [dictionary[#"field_names"] dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: &error];
NSArray* YourArray = json[#"AnArray"];
I didn't find any cocoa method for this task, so I replaced , with & that occurs within {} and then used [string componentsSeparatedByString:#","] method to get it as NSArray. Below is the code
-(NSString *)prepareFields:(NSString *)string {
NSString *remainingString =string;
NSString *newString = #"";
#try {
while ([remainingString rangeOfString:#"{"].location != NSNotFound ) {
NSUInteger from = [remainingString rangeOfString:#"{"].location ,
to =[remainingString rangeOfString:#"}"].location+1 ;
NSString *part = [[remainingString substringWithRange:NSMakeRange(from,to)] stringByReplacingOccurrencesOfString:#"," withString:#"&"];
remainingString = [remainingString substringFromIndex:to];
if([newString isEqualToString:#""])
newString = [part substringWithRange:NSMakeRange([part rangeOfString:#"{"].location,[part rangeOfString:#"}"].location+1)];
newString = [NSString stringWithFormat:#"%#,%#",newString,[part substringWithRange:NSMakeRange([part rangeOfString:#"{"].location,[part rangeOfString:#"}"].location+1)]];
}
}
#catch (NSException *exception) {
NSLog(#"break %#" ,[exception reason]);
}
if([newString isEqualToString:#""])
newString = remainingString;
else
newString = [NSString stringWithFormat:#"%#,%#",newString,remainingString];
return newString;
}
And then called it
NSLog([[dictionary objectForKey:#"form"] componentsSeparatedByString:#","]);
That gave following array
(
"{dBur0z9&nr8r0&R0ru&jrurw&qB5rz9ry}",
"{dBur0z9&nr8r0&R0ru&jrurw&qB5rz9ry}",
"{gr2&Z5uzr&Rwxyr5z0Ar5}",
"",
"^~gr2~cry69v~br9rtyz~Z03r4rsru^~Z5uzr~Uvy3z~dB4srz^5B33",
"()",
9ruI,
evD3rsv3,
"",
HLK,
evDsBAA65,
evDtyvt2s6E,
5B33,
5B33,
5B33,
5B33,
"{6ww}",
SRiTfUV,
5B33,
5B33,
5B33,
5B33 )

NSSet to string separaing by comma

I have the next code for converting NSSet to string separating by comma:
-(NSString *)toStringSeparatingByComma
{
NSMutableString *resultString = [NSMutableString new];
NSEnumerator *enumerator = [self objectEnumerator];
NSString* value;
while ((value = [enumerator nextObject])) {
[resultString appendFormat:[NSString stringWithFormat:#" %# ,",value]];//1
}
NSRange lastComma = [resultString rangeOfString:#"," options:NSBackwardsSearch];
if(lastComma.location != NSNotFound) {
resultString = [resultString stringByReplacingCharactersInRange:lastComma //2
withString: #""];
}
return resultString;
}
It seems that it works, but I get here two warnings:
1. format string is not a string literal (potentially insecure)
2. incompatible pointer types assigning to nsmutablestring from nsstring
How to rewrite it to avoid of warnings?
There is another way to achieve what you are trying to do with fewer lines of code:
You can get an array of NSSet objects using:
NSArray *myArray = [mySet allObjects];
You can convert the array to a string:
NSString *myStr = [myArray componentsJoinedByString:#","];
stringByReplacingCharactersInRange method's return type NSString. You are assigning it to NSMutableString. Use mutable copy.
resultString = [[resultString stringByReplacingCharactersInRange:lastComma //2
withString: #""]mutablecopy]

Resources