Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove double quotes and brackets from NSString

Tags:

string

ios

I have string in this from ["658681","655917","655904"]i want to change this string in this form 658681,655917,655904 how it can be changed? below is my code of string

- (IBAction)Searchbtn:(id)sender {

    NSData *data=[NSJSONSerialization dataWithJSONObject:getmessageIDArray options:kNilOptions error:nil];
    _finalIDStr=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"the final ID Str==%@",_finalIDStr);



}
like image 635
Mishal Awan Avatar asked Dec 09 '22 05:12

Mishal Awan


2 Answers

Use following code:

NSCharacterSet *unwantedChars = [NSCharacterSet characterSetWithCharactersInString:@"\"[]"];
NSString *requiredString = [[_finalIDStr componentsSeparatedByCharactersInSet:unwantedChars] componentsJoinedByString: @""];

It's efficient and effective way to remove as many characters from your string in one single line..

like image 187
Salman Zaidi Avatar answered Dec 11 '22 10:12

Salman Zaidi


this will do it in swift

var stringwithoutquotes = string1.stringByReplacingOccurrencesOfString("\"", withString: "")
var removebracket1 = stringwithoutquotes.stringByReplacingOccurrencesOfString("[", withString: "")
var removebracket2 = removebracket1.stringByReplacingOccurrencesOfString("]", withString: "")

or you could do the entire thing in one line

var string2 = string.stringByReplacingOccurrencesOfString("\"", withString: "").stringByReplacingOccurrencesOfString("[", withString: "").stringByReplacingOccurrencesOfString("]", withString: "")

Here is another cleaner option in swift

var string = "\"hello[]" // string starts as "hello[]
var badchar: NSCharacterSet = NSCharacterSet(charactersInString: "\"[]")
var cleanedstring: NSString = (string.componentsSeparatedByCharactersInSet(badchar) as NSArray).componentsJoinedByString("")
//cleanedstring prints as "hello"

Swift 3:

let string = "\"hello[]" // string starts as "hello[]
let badchar = CharacterSet(charactersIn: "\"[]")
let cleanedstring = string.components(separatedBy: badchar).joined()
//cleanedstring prints as "hello"
like image 24
nsij22 Avatar answered Dec 11 '22 11:12

nsij22