我有问题。我的字符串格式为"abc"
,它有“”。现在我想从abc
获得"abc"
(意味着从字符串中删除“”并仅获取abc)。我怎样才能做到这一点?提前致谢
答案 0 :(得分:2)
NSString *abc = [@"\"abc\"" stringByReplacingOccurencesOfString:@"\"" withString:@""];
答案 1 :(得分:1)
#import <Foundation/Foundation.h>
int main(int argc, const char **argv) {
@autoreleasepool {
NSString *input = @"\"abc\"";
NSArray *elements = [input componentsSeparatedByString:@"\""];
if ([elements count] > 0) {
NSString *element = [elements objectAtIndex:1];
NSLog(@"count=%lu element='%@'", [elements count], element);
}
}
return 0;
}
$ clang -o strsep strsep.m -framework Foundation
$ ./strsep
2013-10-07 11:42:44.274 strsep[34292:707] count=3 element='abc'
答案 2 :(得分:1)
[String replaceOccurrencesOfString:@"\"" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [String length])];
答案 3 :(得分:1)
有一个内置函数,可以让你用另一个子串替换所有出现的子串 - 如果另一个子串被设置为空字符串( @“”),它将有效删除所有出现的子串。你的例子:
NSString * yourNewString = [yourOldString stringByReplacingOccurrencesOfString:@"\"" withString:@""]);
答案 4 :(得分:1)
您可以使用空格替换“空格。”
NSString *some = @"\"abc\"";
NSLog(@"%@",some);
NSString *newString = [some stringByReplacingOccurrencesOfString:@"\"" withString:@""];
NSLog(@"%@",newString);
答案 5 :(得分:0)
我为你写了一个方法,这将完美地运作:(如果你的最后一个字符是“)
- (NSString*) getTheString:(NSString*) yourString{
NSString* answerString = [[NSString alloc]init];
int substrinFrom = 0;
for (NSInteger charIdx=0; charIdx<[yourString length]; charIdx++){
if ( '"' == [yourString characterAtIndex:charIdx]) {
substrinFrom = charIdx;
NSLog(@"%i",substrinFrom);
break;
}
}
answerString = [yourString substringWithRange:NSMakeRange(substrinFrom+1, [yourString length] - substrinFrom -2 )];
return answerString;
}
测试它:
NSString* test = [self getTheString:@"\"Hello this is a test string, and it will work\""];
NSLog(@"%@",test);