ObjC代码:
#pragma mark - bookNameFromString
+(NSString *) bookNameFromString:(NSString *)string{
NSMutableArray *newLineArray = [[NSMutableArray alloc]init];
NSUInteger length = [string length];
unichar buffer[length+1];
[string getCharacters:buffer range:NSMakeRange(0, length)];
NSInteger a = 0;
do {
a = a+ 1;
char current = buffer[a];
if (current == '\n') {
[newLineArray addObject:[NSNumber numberWithInteger:a]];
break;
}
} while (a <= length);
NSString *bookName = nil;
if (newLineArray.count > 0 && newLineArray[0] != 0) {
bookName = [string substringToIndex:[newLineArray[0]integerValue]];
}
return bookName;
}
在Swift中: 转换为swift
在向数组追加值时,会出现错误:无法转换类型&#39; String.CharacterView.Index&#39;预期参数类型&#39; Int&#39;
// MARK: - bookNameFromString
func bookNameFromString(string:String) ->String {
let toFind:Character = "\n"
var newLineArray:[Int] = []
let lengthOfString = string.characters.count
var a = 0
repeat{
a = a + 1
if let index = string.characters.indexOf(toFind) {
newLineArray.append(index) */ERROR: Cannot convert value of type 'String.CharacterView.Index' to expected argument type 'Int'/*
break
}
}while a < lengthOfString
print(newLineArray)
var bookName:String
if newLineArray.count > 0 && newLineArray[0] != 0{
bookName = string.substringToIndex(string.startIndex.advancedBy(newLineArray[0]))
}
return bookName
}
答案 0 :(得分:0)
这是尝试没有缓冲区并检查单个字符
func bookNameFromString(string : String) -> String?
{
// separate string by linefeed character
let array = string.componentsSeparatedByString("\n")
// if string is empty or there is none or one linefeed - exit
guard array.count > 1 else { return nil }
// define a startindex which is 1 if the string starts with linefeed
let startIndex = array[0].isEmpty ? 1 : 0
// if there is no linefeed left - exit
guard array.count > startIndex + 1 else { return nil }
return startIndex == 1 ? "\n" + array[startIndex] : array[startIndex]
}
bookNameFromString("") // -> nil
bookNameFromString("\n") // -> nil
bookNameFromString("\n\n") // -> \n
bookNameFromString("Hello") // -> nil
bookNameFromString("\nHello") // -> nil
bookNameFromString("Hello\n") // -> Hello
bookNameFromString("Hello\nWorld") // -> Hello
bookNameFromString("\nHello\n") // -> \nHello
bookNameFromString("\nHello\nWorld") // -> \nHello