在动态NSString的中间添加一个字符串

时间:2013-01-03 10:49:53

标签: iphone ios ipad

我有NSString,NSString的内容来自网址。我想在这个NSString之后添加一个单词,后跟一个特定的单词。这个NSString会不断变化

例如:

我收到像" hi mac this is ios"这样的数据,这个字符串可能会像这样不断变化 " hi ios this mac" or hi this is mac ios"等等。

我想添加一个像“hello”这样的词,然后添加“mac”总是

" hi mac hello this is ios"
" hi ios this mac hello"
"hi this is mac hello ios"

我该怎么做

4 个答案:

答案 0 :(得分:1)

试试这个......

Yourstring = [Yourstring stringByReplacingOccurrencesOfString:@"mac" withString:@"mac hello "];

答案 1 :(得分:1)

您可以使用:

string = [string stringByReplacingOccurrencesOfString:@"Mac" withString:@"Mac Hello"];

答案 2 :(得分:0)

NSString * str = @“嗨Mac这是”;

if ([str rangeOfString:@"mac" options:NSCaseInsensitiveSearch].location != NSNotFound)
{
    int location = [str rangeOfString:@"mac" options:NSCaseInsensitiveSearch].location;

    NSMutableString *mstr = [[[NSMutableString alloc] initWithString:str] autorelease];
    NSString *strtemp = @"mac";

    [mstr replaceCharactersInRange:NSMakeRange(location, [strtemp length]) withString:[NSString stringWithFormat:@"%@ %@", strtemp, @"hello"]];

    NSLog(@"test  %@", mstr);
}

答案 3 :(得分:0)

如果您不想用mac hello替换mac,那么您可以这样做

NSMutableString *string=[NSMutableString stringWithString:@"hi mac this is ios"];
NSRange range = [string rangeOfString:@"mac"];    
[string insertString:@" hello" atIndex:range.location+3];
NSLog(@"str=%@",string);

输出:

str=hi mac hello this is ios