如何在“#”之前删除字符串?
有一个字符串。如何在“#”之前删除字符串?
的NSString *测试= @ “1997#测试”
我想要的 “#” 之前删除的字符串。
它改变这样的:
的NSString *测试= @ “测试”
你能帮助我吗?
技术上#
之前去除串会离开你 “#TEST”。
无论如何,使用- [NSString componentsSeparatedByString:]
:
test = [[test componentsSeparatedByString:@"#"] lastObject];
注意,这种方法是脆弱的:如果你有2 #
你最终会与刚刚过去的一部分,例如“abc#bar#foo”中的“foo”。
使用lastObject
而不是objectAtIndex:
意味着如果字符串中没有#
,那么您将获得原始字符串而不是崩溃。
NSArray *components=[test componentsSeparatedByString:@"#"];
NSString *test=[components objectAtIndex:1];
它会帮助你
您的代码段中存在一个小错字。 (“NSSting”而不是NSString在第二行)。:-) – 2011-04-08 11:39:36
如果只有曾经打算在字符串中一个哈希符号,你可以简单地使用NSStringcomponentsSeparatedByString
方法返回一个数组,然后简单地摘下的第一个元素数组放入字符串中。
例如:
NSString *test = @"1997#test";
NSArray *stringComponents = [test componentsSeparatedByString:@"#"];
NSString *test = [stringComponents objectAtIndex:1];
使用标准NSString API方法:
NSString* test = @"1997#test";
NSArray* parts = [test componentsSeparatedByString:@"#"];
NSString* result = [parts count] > 1 ? [parts objectAtIndex: 1] : [parts objectAtIndex: 0];
或者,如果这是一个有点太钝(其中我个人认为这是),你可以使用NSString+JavaAPI类别,然后做:
NSString* test = @"1997#test";
NSString* result = [test substringFromIndex: [test indexOf:@"#"] + 1];
你选择了哪一个? – markhunte 2011-04-08 21:27:05
NSString * test = @“Chetan#iPhone#test”;
NSArray * stringComponents = [test componentsSeparatedByString:@“#”];
的for(int i = 0;我< [stringComponents计数];我++)
{
NSString *test = [stringComponents objectAtIndex:i];
if ([test isEqualToString:@"test"] == true)
{
NSLog(@"found");
break;
}
}
不是说这比其他方法更好,但我古董,看看我是否可以做到这一点没有componentsSeparatedByString和objectAtIndex。
NSString* oldString = @"1976#test";
int stringLocation = [oldString rangeOfString:@"#" ].location +1 ;
NSString* newString =[oldString substringWithRange: NSMakeRange (stringLocation,[oldString length] - stringLocation)];
在字符串中是否只存在单个散列/磅(#)符号? – 2011-04-08 11:35:58