我正在尝试将一个复数的字符串拆分为实数和虚数。
我试图在互联网上找到解决方案,但我发现的所有解决方案都删除了分裂字符。
我将在示例中展示我想要做什么:
我有一个这种形式的字符串:-3.5 + 6.7i
我想将字符串拆分为-3.5和+ 6.7i
感谢您的帮助!!!
答案 0 :(得分:1)
这很简单:
NSString *complexNumber = @"-3.5+6.7i";
NSArray *components = [complexNumber componentsSeparatedByString:@"+"];
NSString *realPart = components[0];
NSString *imaginaryPart = [@"+" stringByAppendingString:components[1]];
下一个问题:你将如何分割@"-3.5-6.7i"
?
答案 1 :(得分:1)
试试这个功能。 Haven未对其进行测试,因此可能需要进行一些调整
+ (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;
}
答案 2 :(得分:0)
接受的答案很糟糕,它没有处理任何明显的角落案件。试试这个:
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);