写一个方法,请将任意字符串中的"<" ">"最近的之间的内容删除,并返回其余的字符串;例如:
NSString * str1 = @"<hdadsdtmlsssss></dqdqw>4<5<//dwdq><uioq>";
返回 4 <5;
NSString *str2 = @"<dwqdwqdq>abc<dwdwdw>de<dddd>";
返回 abcde;
半夜被雨吵醒..逛下简书发现达文哥解答了一道iOS面试题, 好久没写算法了..手痒果断来了一发..这一撸竟然就没了1个多小时..T-T..丫的, 睡觉去了..
- (NSString *)filterText:(NSString *)text {
static const unichar leftBracket = '<';
static const unichar rightBracket = '>';
if (text.length > 0) {
unichar *finalText = (unichar *)malloc(sizeof(unichar)*text.length);
int i = 0;
unichar *buffer = NULL;
int j = 0;
if (finalText) {
// 是否应该缓存
bool shouldBuffer = false;
// 缓存开始的Index
int startIndexOfBuffer = -1;
// 上次遇到左括号的Index
int lastLeftBracketIndex = 0;
for (int k = 0; k < text.length; k++) {
unichar _char = [text characterAtIndex:k];
// 若遇到左括号就一直缓存字符, 直至遇到右括号才停止缓存
if (_char == leftBracket) {
shouldBuffer = true;
if (startIndexOfBuffer < 0) {
startIndexOfBuffer = k;
}
lastLeftBracketIndex = k;
if (!buffer) {
buffer = (unichar *)malloc(sizeof(unichar)*(text.length-i));
j = 0;
if (!buffer) {
NSLog(@"开辟空间失败:[");
return nil;
}
}
}
else if (_char == rightBracket) {
// 遇到右括号果断关闭缓存, 可以直接写入了, 等再次遇到左括号才开启缓存
shouldBuffer = false;
}
if (shouldBuffer) {// 记录缓存
buffer[j++] = _char;
}
else if (!buffer) {// 不缓存则直接追加
finalText[i++] = _char;
}
else if(buffer) {// 追加缓存
//validCount就是要取出来的缓存字符个数, 剩下的字符抛弃(从最后一个左括号到右括号前的过滤字符)
int validCount = lastLeftBracketIndex-startIndexOfBuffer;
for (int m = 0; m < validCount; m++) {
finalText[i++] = buffer[m];// 丫的..这里手贱写了个m++, 找错花了好一会!!!差点怀疑人生, 挂不得输出结果老是少1个字符
}
// 重置缓存起点!
startIndexOfBuffer = -1;
free(buffer);
buffer = NULL;
}
}
}
else {
NSLog(@"开辟空间失败:[");
return nil;
}
NSString *fText = nil;
// Raises an exception if characters is NULL, even if length is 0.
if (i > 0) {
fText = [[NSString alloc] initWithCharacters:finalText length:i];
}
free(finalText);
finalText = NULL;
return fText ?: @"";
}
return @"";
}