2011-04-08 119 views
1

有一個字符串。如何在「#」之前刪除字符串?

的NSString *測試= @ 「1997#測試」

我想要的 「#」 之前刪除的字符串。
它改變這樣的:

的NSString *測試= @ 「測試」

你能幫助我嗎?

+0

在字符串中是否只存在單個散列/磅(#)符號? – 2011-04-08 11:35:58

回答

2

技術上#之前去除串會離開你 「#TEST」。

無論如何,使用- [NSString componentsSeparatedByString:]

test = [[test componentsSeparatedByString:@"#"] lastObject]; 

注意,這種方法是脆弱的:如果你有2 #你最終會與剛剛過去的一部分,例如「abc#bar#foo」中的「foo」。

使用lastObject而不是objectAtIndex:意味着如果字符串中沒有#,那麼您將獲得原始字符串而不是崩潰。

0
NSArray *components=[test componentsSeparatedByString:@"#"]; 
NSString *test=[components objectAtIndex:1]; 

它會幫助你

+0

您的代碼段中存在一個小錯字。 (「NSSting」而不是NSString在第二行)。:-) – 2011-04-08 11:39:36

0

如果只有曾經打算在字符串中一個哈希符號,你可以簡單地使用NSStringcomponentsSeparatedByString方法返回一個數組,然後簡單地摘下的第一個元素數組放入字符串中。

例如:

NSString *test = @"1997#test"; 
NSArray *stringComponents = [test componentsSeparatedByString:@"#"]; 
NSString *test = [stringComponents objectAtIndex:1]; 
3

使用標準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]; 
+0

你選擇了哪一個? – markhunte 2011-04-08 21:27:05

-1

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; 

} 

}

1

不是說這比其他方法更好,但我古董,看看我是否可以做到這一點沒有componentsSeparatedByStringobjectAtIndex

NSString* oldString = @"1976#test"; 
int stringLocation = [oldString rangeOfString:@"#" ].location +1 ; 
NSString* newString =[oldString substringWithRange: NSMakeRange (stringLocation,[oldString length] - stringLocation)]; 
相關問題