objective-c 如何在Objective-C中声明一个字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1567564/
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-09-03 22:21:31  来源:igfitidea点击:

How to declare a string in Objective-C?

objective-ccocoastringnsstring

提问by powtac

How do I declare a simple string "test" to a variable?

如何向变量声明一个简单的字符串“test”?

回答by Carl Norum

A C string is just like in C.

AC 字符串就像在 C 中一样。

char myCString[] = "test";

An NSString uses the @character:

NSString 使用以下@字符:

NSString *myNSString = @"test";

If you need to manage the NSString's memory:

如果需要管理 NSString 的内存:

NSString *myNSString = [NSString stringWithFormat:@"test"];
NSString *myRetainedNSString = [[NSString alloc] initWithFormat:@"test"];

Or if you need an editable string:

或者,如果您需要一个可编辑的字符串:

NSMutableString *myMutableString = [NSMutableString stringWithFormat:@"test"];

You can read more from the Apple NSString documentation.

您可以从Apple NSString 文档中阅读更多内容

回答by Jeff Kelley

NSString *testString = @"test";

回答by AnthonyLambert

Standard string assignment can be done like so:

标准字符串分配可以这样完成:

NSString *myTestString = @"abc123";

In addition to the basic allocation there are a whole lot of methods you get when using the NSString Class that you don't get with the Standard Char[] array. That is why Objective programming is better!

除了基本分配之外,在使用 NSString 类时,您还可以获得很多方法,而标准 Char[] 数组则无法获得这些方法。这就是为什么目标编程更好的原因!

For instance filling a string with the contents of a html webpage, with a single line of code!**

例如,用一行代码用 html 网页的内容填充一个字符串!**

Creating and Initializing Strings

创建和初始化字符串

+ string
– init
– initWithBytes:length:encoding:
– initWithBytesNoCopy:length:encoding:freeWhenDone:
– initWithCharacters:length:
– initWithCharactersNoCopy:length:freeWhenDone:
– initWithString:
– initWithCString:encoding:
– initWithUTF8String:
– initWithFormat:
– initWithFormat:arguments:
– initWithFormat:locale:
– initWithFormat:locale:arguments:
– initWithData:encoding:
+ stringWithFormat:
+ localizedStringWithFormat:
+ stringWithCharacters:length:
+ stringWithString:
+ stringWithCString:encoding:
+ stringWithUTF8String:

Creating and Initializing a String from a File

从文件创建和初始化字符串

+ stringWithContentsOfFile:encoding:error:
– initWithContentsOfFile:encoding:error:
+ stringWithContentsOfFile:usedEncoding:error:
– initWithContentsOfFile:usedEncoding:error:

Creating and Initializing a String from an URL

从 URL 创建和初始化字符串

+ stringWithContentsOfURL:encoding:error:
– initWithContentsOfURL:encoding:error:
+ stringWithContentsOfURL:usedEncoding:error:
– initWithContentsOfURL:usedEncoding:error:

If you need a string where you can edit its buffer you want to look at:

如果您需要一个字符串,您可以在其中编辑要查看的缓冲区:

NSMutableString