[英]Splitting string in Objective-C without removing separating string
我正在尝试将复杂数字的字符串拆分为实数和虚数。
我试图在Internet上找到解决方案,但是我发现的所有解决方案都消除了分裂现象。
我将在示例中显示我到底想做什么:
我有一个这样的字符串:-3.5 + 6.7i
我想将字符串分成-3.5和+ 6.7i
谢谢您的帮助!!!
这很简单:
NSString *complexNumber = @"-3.5+6.7i";
NSArray *components = [complexNumber componentsSeparatedByString:@"+"];
NSString *realPart = components[0];
NSString *imaginaryPart = [@"+" stringByAppendingString:components[1]];
下一个问题:如何分割@"-3.5-6.7i"
?
试试这个功能。 尚未测试,因此可能需要进行一些调整
+ (NSMutableArray*)split:(NSString*)string on:(NSArray*)separators
{
NSMutableArray* answer = [[NSMutableArray alloc] init];
NSString* substring = [NSString stringWithString:string];
//slowly shrink the string by taking off strings from the front
while ([substring length] > 0)
{
int first = 0;
//look for the separator that occurs earliest and use that for what you are
//splitting on. There is a slight catch here. If you have separators "abc" and "bc",
//and are looking at string "xabcd", then you will find the strings "x", "a", and
//"bcd" since the separators share common substrings, meaning that the strings
//returned from this function are not guaranteed to start with one of the
//separators.
for (int j = 0; j < [separators count]; j++)
{
//need to start from index 1 so that the substring found before that caused
//the split is not found again at index 0
NSString* toCheck = [substring substringFromIndex:1];
int start = [substring rangeOfString:[separators objectAtIndex:j]].location;
if (start < first)
{
first = start;
}
}
[answer addObject:[substring substringToIndex:start]];
substring = [substring substringFromIndex:start];
}
return answer;
}
公认的答案很糟糕,它无法处理任何明显的极端情况。 尝试这个:
NSString * input = @"-3.5+6.7i";
NSString * const floatRe = @"\\d*(?:\\.\\d*)?";
NSString * const reStr = [NSString stringWithFormat:@"([-+]?%@)([-+]%@)i", floatRe, floatRe];
NSRegularExpression * re = [NSRegularExpression regularExpressionWithPattern:reStr options:(NSRegularExpressionOptions)0 error:NULL];
NSArray * matches = [re matchesInString:input options:(NSMatchingOptions)0 range:NSMakeRange(0, input.length)];
if (matches.count != 1) {
// Fail.
}
NSTextCheckingResult * match = matches[0];
double real = [[input substringWithRange:[match rangeAtIndex:1]] doubleValue];
double imag = [[input substringWithRange:[match rangeAtIndex:2]] doubleValue];
NSLog(@"%lf / %lf", real, imag);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.