Added commonPrefixWithString method to CPString and tests for it.

This commit is contained in:
Abhinav Gupta
2009-11-26 18:13:01 -05:00
committed by Ross Boucher
parent d0a8749986
commit 0575e96b60
2 changed files with 64 additions and 0 deletions
+38
View File
@@ -537,6 +537,44 @@ var CPStringRegexSpecialCharacters = [
return hash;
}
/*!
Returns a string containing characters the receiver and a given string have in common, starting from
the beginning of each up to the first characters that aren't equivalent.
@param aString the string with which to compare the receiver
*/
- (CPString)commonPrefixWithString:(CPString)aString
{
return [self commonPrefixWithString: aString options: 0];
}
/*!
Returns a string containing characters the receiver and a given string have in common, starting from
the beginning of each up to the first characters that aren't equivalent.
@param aString the string with which to compare the receiver
@param aMask options for comparision
*/
- (CPString)commonPrefixWithString:(CPString)aString options:(int)aMask
{
var len = 0, // length of common prefix
min = MIN([aString length], [self length]);
for ( len = 0; len < min; len++ )
{
var lhs = [self characterAtIndex: len],
rhs = [aString characterAtIndex: len];
if (aMask & CPCaseInsensitiveSearch)
{
lhs = [lhs lowercaseString];
rhs = [rhs lowercaseString];
}
if ( lhs != rhs )
break;
}
return [self substringToIndex: len];
}
/*!
Returns a copy of the receiver with all the first letters of words capitalized.
*/
+26
View File
@@ -151,6 +151,32 @@
[self assert:[testStrings[i][0] boolValue] equals:testStrings[i][1]];
}
- (void)testCommonPrefixWithString
{
var testStringsCase = [
["Hello", "Helicopter", "Hel"],
["Tester", "Taser", "T"],
["Abcd", "Abcd", "Abcd"],
["A long string", "A longer string", "A long"]
];
var testStringsCaseless = [
["hElLo", "HeLiCoPtEr", "hEl"],
["tEsTeR", "TaSeR", "t"],
["aBcD", "AbCd", "aBcD"],
["a LoNg StRiNg", "A lOnGeR sTrInG", "a LoNg"]
];
for (var i = 0; i < testStringsCase.length; i++)
[self assert: [testStringsCase[i][0] commonPrefixWithString:testStringsCase[i][1]]
equals: testStringsCase[i][2]];
for (var i = 0; i < testStringsCaseless.length; i++)
[self assert: [testStringsCaseless[i][0] commonPrefixWithString: testStringsCaseless[i][1]
options: CPCaseInsensitiveSearch]
equals: testStringsCaseless[i][2]];
}
- (void)testCapitalizedString
{
var testStrings = [