删除以字符串中的符号开头的单词

时间:2016-05-26 05:16:26

标签: ios objective-c

我正在尝试删除以字符串中的符号开头的单词。

NSSting *string =@"Hello #world #ok";

我正在尝试从此字符串中删除单词"#world""#ok",因为它们以#开头 所以我的字符串现在看起来应该是这样的

"Hello"

5 个答案:

答案 0 :(得分:3)

首先在数组中拆分字符串

 NSArray* arr = [@"Hello #world #ok" componentsSeparatedByString: @" "];

然后检查#

的出现
 NSString *myString;

 for(NSString *str in arr)
  {
    if(![str hasPrefix:@"#"])
      {  myString = [NSString stringWithFormat:@"%@ %@",myString,str];
      }
  }

答案 1 :(得分:2)

1.使用空格的分裂字符串:

NSArray* splitArr = [@"Hello #world #ok" componentsSeparatedByString: @" "];

2.删除包含“#”&amp ;;的字符串创建新字符串

NSMutableString* finalStr = [[NSMutableString alloc] init];
for(NSString* str in splitArr) {
    if(![str hasPrefix:@"#"])
         [finalStr appendString:[NSString stringWithFormat:@"%@ ",str]];
} 

finalStr将是您想要的字符串。

答案 2 :(得分:0)

试试这个:

NSString *str1 = @"Hello your bal = 68094";
NSRange range = [str1 rangeOfString:@"="];
if (range.location != NSNotFound) {
  NSString *newString = [str1 substringToIndex:range.location];
  NSLog(@"%@",newString);
} else {
  NSLog(@"= is not found");
}

答案 3 :(得分:0)

可能在代码下方可以提供帮助:

    NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789"] invertedSet];;

    NSString *string =@"Hello #world #ok";

    NSMutableArray *arr=[[NSMutableArray alloc]initWithArray:[string componentsSeparatedByString:@" "]];

    for (int i=0; i<arr.count; i++) {

        if ([[arr objectAtIndex:i] rangeOfCharacterFromSet:set].location != NSNotFound) {

            string=[string stringByReplacingOccurrencesOfString:[arr objectAtIndex:i] withString:@""];
        }
    }


    string = [string stringByTrimmingCharactersInSet:
                               [NSCharacterSet whitespaceCharacterSet]];

或者:

//add character in set to remove word with that character
    NSCharacterSet * set =[NSCharacterSet characterSetWithCharactersInString:@"#"];

    NSString *string =@"Hello #world #ok";

    NSMutableArray *arr=[[NSMutableArray alloc]initWithArray:[string componentsSeparatedByString:@" "]];

    for (int i=0; i<arr.count; i++) {

        if ([[arr objectAtIndex:i] rangeOfCharacterFromSet:set].location != NSNotFound) {

            string=[string stringByReplacingOccurrencesOfString:[arr objectAtIndex:i] withString:@""];
        }
    }


    string = [string stringByTrimmingCharactersInSet:
                               [NSCharacterSet whitespaceCharacterSet]];

答案 4 :(得分:0)

第1步:

NSArray* splitArr = [@"Hello #world #ok" componentsSeparatedByString: @" "];

第2步:

NSString *myString = @"";
for(NSString *str in splitArr)
{
  NSString *firstLetter = [str substringToIndex:0];
  if(![firstLetter isEqualToString:@"#"])
  {  
     myString = [NSString stringWithFormat:@"%@ %@",myString,str];
  }
}