ios 如何将字符串附加到 NSMutableString

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9180671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 16:41:36  来源:igfitidea点击:

How to append a string to NSMutableString

iosobjective-ciphone

提问by murze

i'm an absolute newbie with objective-c

我是 Objective-c 的绝对新手

with this code

用这个代码

NSMutableString *teststring;
[teststring appendString:@"hey"];
NSLog(teststring);

nothing gets displayed in the console.

控制台中没有显示任何内容。

Surely i'm doing something wrong here... :-)

当然我在这里做错了什么...... :-)

回答by Apurv

You need to create the string first.

您需要先创建字符串。

NSMutableString *teststring = [[NSMutableString alloc]init];

[teststring appendString:@"hey"];

NSLog(teststring);

Now, it will print.

现在,它将打印。

回答by Shmidt

Change first line to

将第一行更改为

NSMutableString *teststring = [NSMutableString string];

回答by PengOne

This line

这条线

NSMutableString *teststring;

simply establishes a pointer, but does not create anything. Instead, you need to create a new instance of NSMutableString, for example:

只是建立一个指针,但不创建任何东西。相反,您需要创建 的新实例NSMutableString,例如:

NSMutableString *teststring = [[NSMutableString alloc] init];
[teststring appendString:@"hey"];
NSLog("%@", teststring);

回答by Sly

Sample:

样本:

NSMutableString *buffer = [[NSMutableString alloc] init]; // retain count = 1. Because of the "alloc", you have to call a release later

[buffer appendString:@"abc"];
NSLog(@"1 : %@", buffer);
[buffer appendString:@"def"];
NSLog(@"2 : %@", buffer);

[buffer release]; // retain count = 0 => delete object from memory

回答by Movses Karapetyan

NSMutableString *tag = [NSMutableString stringWithString: @"hello <td> this is inside td </td> 000999 <><> ..<. ><> 00000 <td>uuuuu</td> vvvvv <td> this is also inside td </td>"];  
    NSRange open = [tag rangeOfString:@"<"]; 
    while(open.location != NSNotFound) 
    {
        NSRange close = [tag rangeOfString:@">"]; 
        NSRange string = NSMakeRange(open.location, close.location-open.location+1);
        [tag replaceCharactersInRange:string withString:@""];               
        open =  [tag rangeOfString:@"<"];
        NSLog(@"%@",tag);
    }