我正在寻找与{#1}}相当的Objective-C。
类似的东西:
TrimStart(string)
但是
- (NSString*)trimStart:(NSString*)inputString withTrimString:(NSString*)trimChars {
return inputString;
}
返回test1233
并不只是从字符串中修剪所有3个。
答案 0 :(得分:2)
我建议将-rangeOfCharacterFromSet与NSAnchoredSearch选项一起使用。 然后在调用-substringFromIndex时使用this的结果来删除字符串开头的字符。
答案 1 :(得分:1)
- (NSString*)trimStart:(NSString*)inputString withTrimString:(NSString*)trimChars
{
NSString *buffer = inputString;
NSInteger i = 0;
NSCharacterSet *charSet = [NSCharacterSet charactersSetWithCharactersInString:trimChars];
while ((i<[buffer length])&&[charSet characterIsMember:[buffer characetrAtIndex:i])
{
i ++;
}
return [buffer substringFromIndex:i];
}
答案 2 :(得分:1)
这应该
+ (NSString*)trimStart:(NSString*)inputString withTrimString:(NSString*)trimChars {
NSCharacterSet* trimSet = [NSCharacterSet characterSetWithCharactersInString:trimChars];
for(NSUInteger i = 0; i < [inputString length]; i++) {
if (![trimSet characterIsMember:[inputString characterAtIndex:i]]) {
return [inputString substringFromIndex:i];
}
}
return @"";
}
答案 3 :(得分:1)
@implementation NSString (Trimming)
-(NSString*)trimCharactersFromStart:(NSString*)characters
{
NSCharacterSet* set = [[NSCharacterSet characterSetWithCharactersInString:characters] invertedSet];
NSRange range = [self rangeOfCharacterFromSet:set];
if(range.location == NSNotFound)
return @"";
else if(range.location != 0)
return [self substringFromIndex:range.location];
else
return self;
}
@end
请注意,如果您尝试修剪字符串开头和结尾的字符,可以使用stringByTrimmingCharactersInSet:
答案 4 :(得分:1)
在我看来,Cocoa字符串库中最接近的是字符串方法stringByTrimmingCharactersInSet:
但是,该方法将从开头和结尾修剪字符。
您可能需要编写自己的trimStart方法。它不会那么难。像这样:
-(NSString *)trimCharacter: (unichar) charToTrim fromStartOfString: (NSString *) string
{
NSUIndex index = 0;
if ([string length] == 0)
return nil;
unichar thisChar = [string characterAtIndex: index];
while (thisChar == charToTrim) do
{
thisChar = [string characterAtIndex: index++];
}
return [string substringFromIndex: index];
}
请注意,有些人建议使用rangeOfCharacterFromSet:options:
,其选项值为NSAnchoredSearch。
这不起作用。以下代码:
NSCharacterSet *theSet = [NSCharacterSet characterSetWithCharactersInString: @"3"];
NSString *stringToTrim = @"333test1233";
NSRange range = [stringToTrim rangeOfCharacterFromSet: theSet options: NSAnchoredSearch];
NSLog(@"Range.location = %d, range.length = %d", range.location, range.length);
返回
Range.location = 0,range.length = 1
这不是你想要的。您想要找到要跳过的所有字符的范围。