如何从字符串中删除分号,括号和双引号?

时间:2018-03-08 10:12:53

标签: ios objective-c nsstring

我有一个这样的字符串:

{
    Result1 = G;
    "Result2" = "";
    Result3 = "1.03";
    Result4 = 6212753389;
}

我如何得到这样的结果:

    Result1 = G
    Result2 = 
    Result3 = 1.03
    Result4 = 6212753389

注意:我正在尝试NSCharacterSet的所有建议。

请帮助我,并提前感谢。

3 个答案:

答案 0 :(得分:3)

错误的问题,或更好地说:错误的方法或错误解释您的问题。 别担心,没关系,我会解释原因。

这是典型的结果:

NSString *str = [myDict description];

或者

NSString *str = [NSString stringWithFormat:@"%@", myDict]; //(which relies on `description` method of `NSDictionary`, that's just an hidden call.

参见文档:

  

NSString使用格式字符串,其语法类似于使用的格式字符串   其他格式化程序对象。它支持为其定义的格式字符   ANSI C函数printf(),加上任何对象的%@(参见String   格式说明符和IEEE printf规范)。如果是对象   响应descriptionWithLocale:消息,NSString发送这样的消息   用于检索文本表示的消息。否则,它发送一个   说明消息。本地化字符串资源描述了如何工作   在本地化字符串中使用和重新排序变量参数。   Source

几乎从不依赖于description,这更多是出于调试目的。例如,根据我的经验,Apple至少改变了一次对象的描述。在ExternalAccessory.framework中,您可以获得具有description的设备的MAC地址(这不是Apple的政策),但仅限于某些iOS版本,并且一旦发现错误,它就会被删除。所以,如果你有依赖它的代码,运气不好。

您想要的是NSDictionary的自定义“打印”。 你能做什么:

NSMutableString *str = [[NSMutableString alloc] init];
for (id aKey in myDict)
{ 
    [str appendFormat:@"\t%@ = %@\n", aKey, myDict[aKey]];
}

这会在NSString的末尾添加额外的“\ n”。您可以将其删除,或使用而不是NSMutableArray

NSMutableArray *array = [[NSMutableArray alloc] init];
for (id aKey in myDict)
{ 
    NSString *aLine = [NSString stringWithFormat:@"\t%@ = %@", aKey, myDict[aKey]];
    [array addObject:aLine];
}
NSString *str = [array componentsJoinedByString:@"\n"];

旁注:为什么“Result2”有引号讨论: Why do some dictionary keys have quotes and others don't when printing from debugger?

Why does string show up in NSDictionary with quotes, but others don't?

答案 1 :(得分:2)

extension String {
var pureString: String {
    return self.removeCharsFromString(arr: ["{", "}", ";", "\""])
}

func removeCharsFromString(arr: [String]) -> String {
    var str = self
    for char in arr {
        str = str.replacingOccurrences(of: String(char), with: "")
    }
    return str
}
}

<强>用法

let str = """
{
Result1 = G;
"Result2" = "";
Result3 = "1.03";
Result4 = 6212753389;
}
"""
print(str.pureString)

答案 2 :(得分:0)

试试这个:     夫特:

let str = "{ Result1 = G; \"Result2\" = \"\"; Result3 = \"1.03\"; Result4 = 6212753389; }"

var new = str.replacingOccurrences(of: "{", with: "")
new = new.replacingOccurrences(of: "\"", with: "")
new = new.replacingOccurrences(of: "}", with: "")
new = new.replacingOccurrences(of: ";", with: "")

print(new)

的OBJ-C:

NSString *str = @"{ Result1 = G; \"Result2\" = \"\"; Result3 = \"1.03\"; Result4 = 6212753389; }";

NSString *new = [str stringByReplacingOccurrencesOfString:@"{" withString:@""];
new = [new stringByReplacingOccurrencesOfString:@"}" withString:@""];
new = [new stringByReplacingOccurrencesOfString:@";" withString:@""];
new = [new stringByReplacingOccurrencesOfString:@"\"" withString:@""];

NSLog(@"%@", new);

添加

  

\ n

换新行。