我有这个字符串,["658681","655917","655904"]我希望在这个表单中更改此字符串658681,655917,655904如何更改?下面是我的字符串代码
- (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);
}
Run Code Online (Sandbox Code Playgroud)
这将在swift中完成
var stringwithoutquotes = string1.stringByReplacingOccurrencesOfString("\"", withString: "")
var removebracket1 = stringwithoutquotes.stringByReplacingOccurrencesOfString("[", withString: "")
var removebracket2 = removebracket1.stringByReplacingOccurrencesOfString("]", withString: "")
Run Code Online (Sandbox Code Playgroud)
或者你可以在一行中完成整个事情
var string2 = string.stringByReplacingOccurrencesOfString("\"", withString: "").stringByReplacingOccurrencesOfString("[", withString: "").stringByReplacingOccurrencesOfString("]", withString: "")
Run Code Online (Sandbox Code Playgroud)
这是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"
Run Code Online (Sandbox Code Playgroud)
斯威夫特3:
let string = "\"hello[]" // string starts as "hello[]
let badchar = CharacterSet(charactersIn: "\"[]")
let cleanedstring = string.components(separatedBy: badchar).joined()
//cleanedstring prints as "hello"
Run Code Online (Sandbox Code Playgroud)
使用以下代码:
NSCharacterSet *unwantedChars = [NSCharacterSet characterSetWithCharactersInString:@"\"[]"];
NSString *requiredString = [[_finalIDStr componentsSeparatedByCharactersInSet:unwantedChars] componentsJoinedByString: @""];
Run Code Online (Sandbox Code Playgroud)
这是从一行中删除字符串中的多个字符的高效且有效的方法.
小智 5
Swift 4(字符串数组)我想将字符串数组转换为字符串文本以放置在 TextView 中:
FROM
[“马”,“猫”,“狗”]
TO
马
猫狗
var stringArray = ["horse","cat","dog"]
var stringArrayCleaned = stringArray.description.replacingOccurrences(of: "\"", with: "").replacingOccurrences(of: ",", with: "\n").replacingOccurrences(of: "[", with: "").replacingOccurrences(of: "]", with: "").replacingOccurrences(of: " ", with: "")
print(stringArrayCleaned)
Run Code Online (Sandbox Code Playgroud)