前言
最先接觸編程的知識是在大學里面萌腿,大學里面學了一些基礎(chǔ)的知識限匣,c
語言,java
語言,單片機的匯編
語言等米死;大學畢業(yè)后就開始了app
的開發(fā)之路锌历,先使用oc
進行iOS
的app
開發(fā),后面應(yīng)公司需求峦筒,又相繼學習了java
語言并使用java
語言進行Android
的app
開發(fā)究西,后來微信開放了小程序,應(yīng)公司需求物喷,又學習了小程序的相關(guān)知識卤材,js
、css
峦失、html
等扇丛,腦袋里面有了這么多的編程語言,有時候會有點混亂尉辑,因此想到了把這些編程語言的一些內(nèi)容進行對比帆精、梳理,可以找到他們的相同點和不同點隧魄,結(jié)果是很好的卓练,讓自己的知識更加有深度了,也更加全面了购啄。這篇文章是第一篇襟企,選擇的是字符串string
,后續(xù)會繼續(xù)更新其他內(nèi)容的對比狮含。
正在前往全棧的路上M绲俊>ァ旅择!
編程語言對比系列:一崇摄、字符串的基本使用
大綱為
名詞解釋
-
code point
: 用來表示unicode
編碼表中的字符character
的一個十六進制
的數(shù)字(日常使用中十六
進制锦亦、十
進制數(shù)字都是可以的)疲陕,a hexadecimal number that is used to represent that character in computer data
灰署, 如 :code point
0x4E00
對應(yīng)的character
為一
;code point
0x41
對應(yīng)的character
為A
; code unit
: 表示一個unicode
編碼表中的字符character
所需要的二進制位數(shù)bits
腺怯,A Unicode code unit is a bit size used by a particular Unicode encoding,For example UTF-8 has a code unit size of 8 bits and UTF-16 has 16 and UTF-32 has 32
泳赋,也可以理解為識別
一個unicode
字符所需要的二進制位數(shù)bits
屿愚,不夠的會被舍棄掉code point
—>code unit
—>string
屬性/方法
一汇跨、初始化
OC init
通用
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER;
初始化一個
空
的字符串@""
- 方法
- (instancetype)init NS_DESIGNATED_INITIALIZER;
+ (instancetype)string;
- 例子
NSString *str;
NSString *str2;
NSLog(@"%@", str);
NSLog(@"%@", str2);
NSLog(@"-----------");
str = [[NSString alloc] init];
str2 = [NSString string];
NSLog(@"%@", str);
NSLog(@"%@", str2);
NSLog(@"-----------");
//打印:
(null)
(null)
-----------
-----------
二進制
NSData
(準確的說應(yīng)該是十六進制
)
- 方法
- (nullable instancetype)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding;
- 例子
NSData *data = [@"one" dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@", data);
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", str);
//打印:
<6f6e65>
one
//如果編碼方式為 NSUnicodeStringEncoding :
<6f6e65>
潮
- 小結(jié)
同樣的二進制數(shù)據(jù)娱据,因為編碼方式的不同蚪黑,獲取到的結(jié)果也不同,優(yōu)先使用
NSUTF8StringEncoding
-
編碼方式對應(yīng)的所需字節(jié)數(shù)如下:
-
UTF-8
編碼方式處理二進制數(shù)6f6e65
,6f
忌穿、6e
抒寂、65
,看成是三個單元處理掠剑,在ASCII碼表中對應(yīng)的值依次為o
屈芜、n
、e
朴译,所以輸出one
-
Unicode
編碼方式處理二進制數(shù)6f6e65
井佑,6f6e
65
,看成是兩個單元處理眠寿,一個是完整的6f6e
(保留)躬翁,一個不是完整的65(舍棄),在Unicode編碼表中對應(yīng)的值為漢字潮
盯拱,所以輸出潮
- 所以得到的結(jié)果如上姆另,?
-
通過字節(jié)
bytes
- 方法
//bytes : 字節(jié)數(shù),從緩存buffer中讀取坟乾,是指向buffer地址的指針,指向的是在緩存中的地址
//len : 需要讀取bytes的長度蝶防,如bytes為3甚侣,len參數(shù)為1,則只會讀取bytes中的前1個byte
//encoding : 編碼方式
//freeBuffer : 操作之后是否釋放掉內(nèi)存
- (nullable instancetype)initWithBytes:(const void *)bytes length:(NSUInteger)len encoding:(NSStringEncoding)encoding;
- (nullable instancetype)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)len encoding:(NSStringEncoding)encoding freeWhenDone:(BOOL)freeBuffer; /* "NoCopy" is a hint */
- 例子
NSData *data = [@"one" dataUsingEncoding:NSUTF8StringEncoding];
const void *bytes = [data bytes];
NSLog(@"%p", bytes);
NSString *str = [[NSString alloc] initWithBytes:bytes length:data.length encoding:NSUTF8StringEncoding];
NSLog(@"%@", str);
//輸出:
0x6000000035e0
one
當length參數(shù)傳1時
0x600000017600
o
- 小結(jié)
- 從緩存
buffer
中讀取length
長度的字節(jié)bytes
構(gòu)建字符串
- 從緩存
字符
characters
- 方法
- (instancetype)initWithCharactersNoCopy:(unichar *)characters length:(NSUInteger)length freeWhenDone:(BOOL)freeBuffer; /* "NoCopy" is a hint */
- (instancetype)initWithCharacters:(const unichar *)characters length:(NSUInteger)length;
+ (instancetype)stringWithCharacters:(const unichar *)characters length:(NSUInteger)length;
- 例子
// 43 间学、0x2b 殷费、'+' 這些輸出的都是 +
const unichar ch = 43;
NSString *str = [[NSString alloc] initWithCharacters:&ch length:3];
NSLog(@"%@", str);
//輸出:
+
unichar ch[3];
ch[0] = '+';
ch[1] = 43;
ch[2] = 0x2b;
NSString *str = [[NSString alloc] initWithCharacters:ch length:sizeof(ch) / sizeof(unichar)];
NSLog(@"%@", str);
// 輸出:
+++
- 小結(jié)
- 通過
unicode
字符構(gòu)建字符串,可以使用十六進制
低葫、十進制
详羡、字符
- 通過
通過
OC
字符串NSString
- 方法
//通過其他"oc字符串"初始化
- (instancetype)initWithString:(NSString *)aString;
+ (instancetype)stringWithString:(NSString *)string;
//通過其他"oc字符串"初始化,帶有參數(shù)的嘿悬,可以作為字符串拼接使用
- (instancetype)initWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
- (instancetype)initWithFormat:(NSString *)format arguments:(va_list)argList NS_FORMAT_FUNCTION(1,0);
+ (instancetype)stringWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
//帶有本地話的初始化
- (instancetype)initWithFormat:(NSString *)format locale:(nullable id)locale, ... NS_FORMAT_FUNCTION(1,3);
- (instancetype)initWithFormat:(NSString *)format locale:(nullable id)locale arguments:(va_list)argList NS_FORMAT_FUNCTION(1,0);
+ (instancetype)localizedStringWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
- 例子
//通過其他“oc字符串”直接量初始化
NSString *str = [[NSString alloc] initWithString:@"one"];
NSLog(@"%@", str);
NSString *str2 = [NSString stringWithString:@"one"];
NSLog(@"%@", str2);
//輸出:
one
one
//
int age = 18;
NSString *ageStr = [NSString stringWithFormat:@"小明今年%d歲", age];
NSLog(@"%@", ageStr);
//輸出:
小明今年18歲
- 小結(jié)
-
如果是通過
字符串常量
進行初始化实柠,不推薦使用上面方法,使用下面的寫法NSString *str = @"one";
-
c字符串
CString
- 方法
//把c字符串用encoding編碼方式轉(zhuǎn)化為OC字符串
- (nullable instancetype)initWithCString:(const char *)nullTerminatedCString encoding:(NSStringEncoding)encoding;
+ (nullable instancetype)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc;
//把c字符串用UTF-8編碼方式轉(zhuǎn)化為OC字符串
- (nullable instancetype)initWithUTF8String:(const char *)nullTerminatedCString;
+ (nullable instancetype)stringWithUTF8String:(const char *)nullTerminatedCString;
- 例子
//按照指定編碼方式把c字符串轉(zhuǎn)化為oc字符串
const char *cStr = "c string";
NSString *str = [NSString stringWithCString:cStr encoding:NSUTF8StringEncoding];
NSLog(@"%@", str);
//輸出
c string
//如果使用的是NSUnicodeStringEncoding編碼方式善涨,輸出為:
撓獴物湧
//按照UTF-8編碼方式把c字符串轉(zhuǎn)化為oc字符串
const char *cStr = "c string";
NSString *str = [NSString stringWithUTF8String:cStr];
NSLog(@"%@", str);
//輸出:
c string
- 小結(jié)
- 相同的
c
字符串窒盐,使用不同的編碼方式得到的結(jié)果不一樣,優(yōu)先使用NSUTF8StringEncoding
編碼方式
- 相同的
通過URL
NSURL
-
方法
//使用指定的編碼方式 - (nullable instancetype)initWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error; + (nullable instancetype)stringWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error; - (nullable instancetype)initWithContentsOfURL:(NSURL *)url usedEncoding:(nullable NSStringEncoding *)enc error:(NSError **)error; + (nullable instancetype)stringWithContentsOfURL:(NSURL *)url usedEncoding:(nullable NSStringEncoding *)enc error:(NSError **)error; // 把字符串寫入到url的方法為: - (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)useAuxiliaryFile encoding:(NSStringEncoding)enc error:(NSError **)error;
-
例子
NSURL *url = [NSURL URLWithString:@"https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/LoadingResources/Strings/Strings.html#//apple_ref/doc/uid/10000051i-CH6"]; NSError *error = nil; NSString *str = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error]; if (!error) { NSLog(@"成功---"); NSLog(@"%@", str); } else { NSLog(@"失敗---"); } //輸出: 成功--- <!DOCTYPE html> <html lang="en"> <head> <title>String Resources</title> <meta http-equiv="X-UA-Compatible" content="IE=7"> <meta charset="utf-8"> <meta id="book-resource-type" name="book-resource-type" content="Guide"> <meta scheme="apple_ref" id="identifier" name="identifier" content="http://apple_ref/doc/uid/10000051i"> <meta id="document-version" name="document-version" content="7.5.1"> <meta id="build" name="build" content="616ed7ce2df6736fb09643756e2ae753" /> <meta id="chapterId" name="chapterId" content="10000051i-CH6"> <meta id="date" name="date" content="2016-03-21"> <meta id="description" name="description" content="Explains how to work with nib and bundle resources in apps."> <meta id="book-title" name="book-title" content="Resource Programming Guide"> <meta id="book-root" name="book-root" content="../"> <meta id="book-json" name="book-json" content="../book.json"> <meta id="devcenter" name="devcenter" content="Mac Dev Center"> <meta id="devcenter-url" name="devcenter-url" content="http://developer.apple.com/devcenter/mac"> <meta id="reflib" name="reflib" content="Guides and Sample Code"> <meta id="book-assignments" name="book-assignments" content="{Type/Guide}, {Topic/Data Management/File Management}"> <meta id="copyright" name="copyright" content="Copyright 2018 Apple Inc. All Rights Reserved."> <meta id="xcode-display" name="xcode-display" content="render"> <meta id="IndexTitle" name="IndexTitle" content="Resource Programming Guide: String Resources"> <meta id="resources-uri" name="resources-uri" content="../../../../../Resources/1274"> <link id="book-index-page" rel="Start" title="Resource Programming Guide" type="text/html" href="../index.html"> <link id="next-page" rel="Next" type="text/html" href="../ImageSoundResources/ImageSoundResources.html"> <link id="previous-page" rel="Prev" type="text/html" href="../CocoaNibs/CocoaNibs.html"> <link rel="stylesheet" type="text/css" href="../../../../../Resources/1274/CSS/screen.css"> <!-- xcode_css --> <link rel="stylesheet" type="text/css" href="../../../../../Resources/1274/CSS/feedback.css"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <meta id="platforms" name="platforms" content=""> </head> <body><a name="http://apple_ref/doc/uid/10000051i-CH6" title="String Resources"></a> <div id="_omniture_top"> <!-- SiteCatalyst code version: H.8. Copyright 1997-2006 Omniture, Inc. --> <script type="text/javascript"> /* RSID: */ var s_account="appleglobal,appleusdeveloper,dappdeveloperlib" </script> <script type="text/javascript" src="https://www.apple.com/metrics/scripts/s_code_h.js"></script> <script type="text/javascript"> s.pageName=AC.Tracking.pageName(); s.channel="www.us.developer" /************* DO NOT ALTER ANYTHING BELOW THIS LINE ! **************/ var s_code=s.t();if(s_code)document.write(s_code)</script> <!-- End SiteCatalyst code version: H.8. --> </div> <div id="adcHeader" class="hideOnPrint hideInXcode"> <div id='ssi_Header' class="hideInXcode unified"> <a id="ssi_LibraryTitle" href='../../../../../navigation/'>Guides and Sample Code</a> <a id="ssi_AppleDeveloperConnection" >Developer</a> <div id='ssi_SearchButton' role="button" title="Search">Search</div> </div> <form id='ssi_SearchMenu' method='get' action='../../../../../search/' accept-charset='utf-8'> <label for='adcsearch'>Search Guides and Sample Code</label> <input type='search' id='ssi_SearchField' name='q' accesskey='s' results='5' /> </form> </div> <header id="header"> <div id="title" role="banner"> <h1>Resource Programming Guide</h1> <span id="file_links"> <a id="PDF_link" role="button" tabindex='4' rel="alternate" title="Download PDF"><span id="pdf_icon"></span>PDF</a> <a id="Companion_link" role="button" tabindex='3' title="Download Companion File"><span id="companion_icon"></span>Companion File</a> </span> </div> <ul id="headerButtons" class="hideOnPrint" role="toolbar"> <li id="toc_button" style="display:none"> <button tabindex="5" id="table_of_contents" class="open" role="checkbox" aria-label="Show Table of Contents"><span class="disclosure"></span>Table of Contents</button> </li> <li id="jumpto_button" style="display:none" role="navigation"><select tabindex="6" id="jumpTo"><option value="top">Jump To…</option></select></li> <li id="downloadSample_button" style="display:none"> <a id="Sample_link"><button id="Sample_button">Download Sample Code</button></a> </li> </ul> </header> <nav id="tocContainer" tabindex="7"> <ul id="toc" role="tree"></ul> </nav> <article id="contents" tabindex="0" role="main"> <div id="pageNavigationLinks_top" class="pageNavigationLinks"> <a class='nextLink' rel='next' href='../ImageSoundResources/ImageSoundResources.html'>Next</a><a class='previousLink' rel='prev' href='../CocoaNibs/CocoaNibs.html'>Previous</a> </div> <a id="top" name="top"></a> <a id="INDEX" href="../index.html" style="display:none;"></a> <a name="http://apple_ref/doc/uid/10000051i-CH6-SW1" title="String Resources"></a><h1 id="pageTitle">String Resources</h1><p><a name="http://apple_ref/doc/uid/10000051i-CH6-DontLinkElementID_5"></a><a name="http://apple_ref/doc/uid/10000051i-CH6-DontLinkElementID_6"></a>An important part of the localization process is to localize all of the text strings displayed by your application. By their nature, strings located in <span class="pediaLink" data-header="Nib file" data-contents="A nib file is a special type of resource file that you use to store the user interfaces of iOS and Mac apps. "><a href="../../../../General/Conceptual/DevPedia-CocoaCore/NibFile.html#//apple_ref/doc/uid/TP40008195-CH34" data-renderer-version="1" target="_self">nib files</a></span> can be readily localized along with the rest of the nib file contents. Strings embedded in your code, however, must be extracted, localized, and then reinserted back into your code. To simplify this process—and to make the maintenance of your code easier—OS X and iOS provide the infrastructure needed to separate strings from your code and place them into resource files where they can be localized easily.</p><p>Resource files that contain localizable strings are referred to as <em class="newTerm">strings</em> files because of their filename extension, which is <code>.strings</code>. You can create strings files manually or programmatically depending on your needs. The standard strings file format consists of one or more key-value pairs along with optional comments. The key and value in a given pair are strings of text enclosed in double quotation marks and separated by an equal sign. (You can also use a property list format for strings files. In such a case, the top-level node is a dictionary and each key-value pair of that dictionary is a string entry.) </p><p><span class="content_text">Listing 2-1</span> shows a simple strings file that contains non-localized entries for the default language. When you need to display a string, you pass the string on the left to one of the available string-loading routines. What you get back is the matching value string containing the text translation that is most appropriate for the current user. For the development language, it is common to use the same string for both the key and value, but doing so is not required.</p><a name="http://apple_ref/doc/uid/10000051i-CH6-SW7" title="Listing 2-1A simple strings file"></a><p class="codesample clear"><strong class="caption_number">Listing 2-1</strong> A simple strings file</p><div class="codesample clear"><table><tr><td scope="row"><pre>/* Insert Element menu item */<span></span></pre></td></tr><tr><td scope="row"><pre>"Insert Element" = "Insert Element";<span></span></pre></td></tr><tr><td scope="row"><pre>/* Error string used for unknown error types. */<span></span></pre></td></tr><tr><td scope="row"><pre>"ErrorString_1" = "An unknown error occurred.";<span></span></pre></td></tr></table></div><p>A typical application has at least one strings file per localization, that is, one strings file in each of the <span class="pediaLink" data-header="Bundle" data-contents="A bundle is a directory in the file system that groups executable code and related resources such as images and sounds together in one place. "><a href="../../../../General/Conceptual/DevPedia-CocoaCore/Bundle.html#//apple_ref/doc/uid/TP40008195-CH4" data-renderer-version="1" target="_self">bundle’s</a></span> <code>.lproj</code> subdirectories. The name of the default strings file is <code><a name="http://apple_ref/doc/uid/10000051i-CH6-DontLinkElementID_7"></a>Localizable.strings</code> but you can create strings files with any file name you choose. Creating strings files is discussed in more depth in <span class="content_text"><a href="#//apple_ref/doc/uid/10000051i-CH6-SW5" data-renderer-version="1">Creating Strings Resource Files</a></span>. </p><div class="notebox"><aside><a name="http://apple_ref/doc/uid/10000051i-CH6-SW4" title="Note"></a><p><strong>Note:</strong> It is recommended that you save strings files using the UTF-8 encoding, which is the default encoding for standard strings files. Xcode automatically transcodes strings files from UTF-8 to UTF-16 when they’re copied into the product. For more information about the standard strings file format, see <span class="content_text"><a href="#//apple_ref/doc/uid/10000051i-CH6-SW5" data-renderer-version="1">Creating Strings Resource Files</a></span>. For more information about Unicode and its text encodings, go to <span class="content_text"><a class="urlLink" rel="external">http://www.unicode.org/</a></span> or <span class="content_text"><a class="urlLink" rel="external">http://en.wikipedia.org/wiki/Unicode</a></span>.</p><p></p></aside></div><p>The loading of string resources (both localized and nonlocalized) ultimately relies on the bundle and internationalization support found in both OS X and iOS. For information about bundles, see <em><a href="../../../../CoreFoundation/Conceptual/CFBundles/Introduction/Introduction.html#//apple_ref/doc/uid/10000123i" data-renderer-version="1" target="_self">Bundle Programming Guide</a></em>. For more information about internationalization and localization, see <em><a href="../../../../MacOSX/Conceptual/BPInternational/Introduction/Introduction.html#//apple_ref/doc/uid/10000171i" data-renderer-version="1" target="_self">Internationalization and Localization Guide</a></em>. </p><section><a name="http://apple_ref/doc/uid/10000051i-CH6-SW5" title="Creating Strings Resource Files"></a><h2 class="jump">Creating Strings Resource Files</h2><p>Although you can create strings files manually, it is rarely necessary to do so. If you write your code using the appropriate string-loading macros, you can use the <code>genstrings</code> command-line tool to extract those strings and create strings files for you. </p><p>The following sections describe the process of how to set up your source files to facilitate the use of the <code>genstrings</code> tool. For detailed information about the tool, see <code><!--a target="_self" -->genstrings<!--/a--></code> man page.</p><section><a name="http://apple_ref/doc/uid/10000051i-CH6-96936" title="Choosing Which Strings to Localize"></a><h3 class="jump">Choosing Which Strings to Localize</h3><p>When it comes to localizing your application’s interface, it is not always appropriate to localize every string used by your application. Translation is a costly process, and translating strings that are never seen by the user is a waste of time and money. Strings that are not displayed to the user, such as notification names used internally by your application, do not need to be translated. Consider the following example: </p><div class="codesample clear"><table><tr><td scope="row"><pre>if (CFStringHasPrefix(value, CFSTR("-")) { CFArrayAppendValue(myArray, value);};<span></span></pre></td></tr></table></div><p>In this example, the string “<code>-</code>” is used internally and is never seen by the user; therefore, it does not need to be placed in a strings file. </p><p>The following code shows another example of a string the user would not see. The string <code>"%d %d %s"</code> does not need to be localized, since the user never sees it and it has no effect on anything that the user does see. </p><div class="codesample clear"><table><tr><td scope="row"><pre>matches = sscanf(s, "%d %d %s", &first, &last, &other);<span></span></pre></td></tr></table></div><p>Because nib files are localized separately, you do not need to include strings that are already located inside of a nib file. Some of the strings you should localize, however, include the following:</p><ul class="ul"><li class="li"><p>Strings that are programmatically added to a window, panel, view, or control and subsequently displayed to the user. This includes strings you pass into standard routines, such as those that display alert boxes.</p></li><li class="li"><p>Menu item title strings if those strings are added programmatically. For example, if you use custom strings for the Undo menu item, those strings should be in a strings file. </p></li><li class="li"><p>Error messages that are displayed to the user.</p></li><li class="li"><p>Any boilerplate text that is displayed to the user.</p></li><li class="li"><p>Some strings from your application’s information property list (<code>Info.plist</code>) file; see <em><a href="../../../../MacOSX/Conceptual/BPRuntimeConfig/000-Introduction/introduction.html#//apple_ref/doc/uid/10000170i" data-renderer-version="1" target="_self">Runtime Configuration Guidelines</a></em>.</p></li><li class="li"><p>New file and document names.</p></li></ul></section><section><a name="http://apple_ref/doc/uid/10000051i-CH6-SW8" title="About the String-Loading Macros"></a><h3 class="jump">About the String-Loading Macros</h3><p>The Foundation and Core Foundation <span class="pediaLink" data-header="Framework" data-contents="A framework is a bundle (a structured directory) that contains a dynamic shared library along with associated resources, such as nib files, image files, and header files. "><a href="../../../../General/Conceptual/DevPedia-CocoaCore/Framework.html#//apple_ref/doc/uid/TP40008195-CH56" data-renderer-version="1" target="_self">frameworks</a></span> define the following macros to make loading strings from a strings file easier:</p><ul class="ul"><li class="li"><p>Core Foundation macros:</p><ul class="nested"><li class="nested li"><p><code><a target="_self" class="urlLink">CFCopyLocalizedString</a></code></p></li><li class="nested li"><p><code><a target="_self" class="urlLink">CFCopyLocalizedStringFromTable</a></code></p></li><li class="nested li"><p><code><a target="_self" class="urlLink">CFCopyLocalizedStringFromTableInBundle</a></code></p></li><li class="nested li"><p><code><a target="_self" class="urlLink">CFCopyLocalizedStringWithDefaultValue</a></code></p></li></ul></li><li class="li"><p>Foundation macros:</p><ul class="nested"><li class="nested li"><p><code><a target="_self" class="urlLink">NSLocalizedString</a></code></p></li><li class="nested li"><p><code><a target="_self" class="urlLink">NSLocalizedStringFromTable</a></code></p></li><li class="nested li"><p><code><a target="_self" class="urlLink">NSLocalizedStringFromTableInBundle</a></code></p></li><li class="nested li"><p><code><a target="_self" class="urlLink">NSLocalizedStringWithDefaultValue</a></code></p></li></ul></li></ul><p>You use these macros in your source code to load strings from one of your application’s strings files. The macros take the user’s current language preferences into account when retrieving the actual string value. In addition, the <code>genstrings</code> tool searches for these macros and uses the information they contain to build the initial set of strings files for your application.</p><p>For additional information about how to use these macros, see <span class="content_text"><a href="#//apple_ref/doc/uid/20000005-97055" data-renderer-version="1">Loading String Resources Into Your Code</a></span>.</p></section><section><a name="http://apple_ref/doc/uid/10000051i-CH6-SW9" title="Using the genstrings Tool to Create Strings Files"></a><h3 class="jump">Using the genstrings Tool to Create Strings Files</h3><p>At some point during your development, you need to create the strings files needed by your code. If you wrote your code using the Core Foundation and Foundation macros, the simplest way to create your strings files is using the <a name="http://apple_ref/doc/uid/10000051i-CH6-DontLinkElementID_8"></a><code>genstrings</code> command-line tool. You can use this tool to generate a new set of strings files or update a set of existing files based on your source code. </p><p>To use the <code>genstrings</code> tool, you typically provide at least two arguments:</p><ul class="ul"><li class="li"><p>A list of source files</p></li><li class="li"><p>An optional output directory</p></li></ul><p>The <code>genstrings</code> tool can parse C, <span class="pediaLink" data-header="Objective-C" data-contents="Objective-C defines a small but powerful set of extensions to the ANSI C programming language that enables sophisticated object-oriented programming. "><a href="../../../../General/Conceptual/DevPedia-CocoaCore/ObjectiveC.html#//apple_ref/doc/uid/TP40008195-CH43" data-renderer-version="1" target="_self">Objective-C</a></span>, and Java code files with the <code>.c</code>, <code>.m</code>, or <code>.java</code> filename extensions. Although not strictly required, specifying an output directory is recommended and is where <code>genstrings</code> places the resulting strings files. In most cases, you would want to specify the directory containing the project resources for your development language. </p><p>The following example shows a simple command for running the <code>genstrings</code> tool. This command causes the tool to parse all Objective-C source files in the current directory and put the resulting strings files in the <code>en.lproj</code> subdirectory, which must already exist. </p><div class="codesample clear"><table><tr><td scope="row"><pre>genstrings -o en.lproj *.m<span></span></pre></td></tr></table></div><p>The first time you run the <code>genstrings</code> tool, it creates a set of new strings files for you. Subsequent runs replace the contents of those strings files with the current string entries found in your source code. For subsequent runs, it is a good idea to save a copy of your current strings files before running <code>genstrings</code>. You can then diff the new and old versions to determine which strings were added to (or changed in) your project. You can then use this information to update any already localized versions of your strings files, rather than replacing those files and localizing them again. </p><p>Within a single strings file, each key must be unique. Fortunately, the <code>genstrings</code> tool is smart enough to coalesce any duplicate entries it finds. When it discovers a key string used more than once in a single strings file, the tool merges the comments from the individual entries into one comment string and generates a warning. (You can suppress the duplicate entries warning with the <code>-q</code> option.) If the same key string is assigned to strings in different strings files, no warning is generated. </p><p>For more information about using the <code>genstrings</code> tool, see the <code><!--a target="_self" -->genstrings<!--/a--></code> man page. </p></section><section><a name="http://apple_ref/doc/uid/10000051i-CH6-SW10" title="Creating Strings Files Manually"></a><h3 class="jump">Creating Strings Files Manually</h3><p>Although the <code>genstrings</code> tool is the most convenient way to create strings files, you can also create them manually. To create a strings file manually, create a new file in TextEdit (or your preferred text-editing application) and save it using the Unicode UTF-8 encoding. (When saving files, TextEdit usually chooses an appropriate encoding by default. To force a specific encoding, you must change the save options in the application preferences.) The contents of this file consists of a set of key-value pairs along with optional comments describing the purpose of each key-value pair. Key and value strings are separated by an equal sign, and the entire entry must be terminated with a semicolon character. By convention, comments are enclosed inside C-style comment delimiters (<code>/*</code> and <code>*/</code>) and are placed immediately before the entry they describe. </p><p><span class="content_text">Listing 2-2</span> shows the basic format of a strings file. The entries in this example come from the English version of the <code>Localizable.strings</code> file from the TextEdit application. The string on the left side of each equal sign represents the key, and the string on the right side represents the value. A common convention when developing applications is to use a key name that equals the value in the language used to develop the application. Therefore, because TextEdit was developed using the English language, the English version of the <code>Localizable.strings</code> file has keys and values that match.</p><a name="http://apple_ref/doc/uid/10000051i-CH6-SW2" title="Listing 2-2Strings localized for English"></a><p class="codesample clear"><strong class="caption_number">Listing 2-2</strong> Strings localized for English</p><div class="codesample clear"><table><tr><td scope="row"><pre>/* Menu item to make the current document plain text */<span></span></pre></td></tr><tr><td scope="row"><pre>"Make Plain Text" = "Make Plain Text";<span></span></pre></td></tr><tr><td scope="row"><pre>/* Menu item to make the current document rich text */<span></span></pre></td></tr><tr><td scope="row"><pre>"Make Rich Text" = "Make Rich Text";<span></span></pre></td></tr></table></div><p><span class="content_text">Listing 2-3</span> shows the German translation of the same entries. These entries also live inside a file called <code>Localizable.strings</code>, but this version of the file is located in the German language project directory of the TextEdit application. Notice that the keys are still in English, but the values assigned to those keys are in German. This is because the key strings are never seen by end users. They are used by the code to retrieve the corresponding value string, which in this case is in German. </p><a name="http://apple_ref/doc/uid/10000051i-CH6-SW6" title="Listing 2-3Strings localized for German"></a><p class="codesample clear"><strong class="caption_number">Listing 2-3</strong> Strings localized for German</p><div class="codesample clear"><table><tr><td scope="row"><pre>/* Menu item to make the current document plain text */<span></span></pre></td></tr><tr><td scope="row"><pre>"Make Plain Text" = "In reinen Text umwandeln";<span></span></pre></td></tr><tr><td scope="row"><pre>/* Menu item to make the current document rich text */<span></span></pre></td></tr><tr><td scope="row"><pre>"Make Rich Text" = "In formatierten Text umwandeln";<span></span></pre></td></tr></table></div></section><section><a name="http://apple_ref/doc/uid/10000051i-CH6-96996" title="Detecting Non-localizable Strings"></a><h3 class="jump">Detecting Non-localizable Strings</h3><p>AppKit–based applications can take advantage of built-in support to detect strings that do not need to be localized and those that need to be localized but currently are not. To use this built-in support, set user defaults or add launch arguments when running your app. Specify a Boolean value to indicate whether the user default should be enabled or disabled. The available user defaults are as follows:</p><ul class="ul"><li class="li"><p>The <code>NSShowNonLocalizableStrings</code> user default identifies strings that are not localizable. The strings are logged to the shell in upper case. This option occasionally generates some false positives but is still useful overall. </p></li><li class="li"><p>The <code>NSShowNonLocalizedStrings</code> user default locates strings that were meant to be localized but could not be found in the application’s existing strings files. You can use this user default to catch problems with out-of-date localizations. </p></li></ul><p>For example, to use the <code>NSShowNonLocalizedStrings</code> user default with the TextEdit application, enter the following in Terminal:</p><div class="codesample clear"><table><tr><td scope="row"><pre>/Applications/TextEdit.app/Contents/MacOS/TextEdit -NSShowNonLocalizedStrings YES<span></span></pre></td></tr></table></div></section></section><section><a name="http://apple_ref/doc/uid/20000005-97055" title="Loading String Resources Into Your Code"></a><a name="http://apple_ref/doc/uid/10000051i-CH6-97055-CJBFDJGF" title="Loading String Resources Into Your Code"></a><h2 class="jump">Loading String Resources Into Your Code</h2><p>The Core Foundation and Foundation frameworks provide macros for retrieving both localized and nonlocalized strings stored in strings files. Although the main purpose of these macros is to load strings at runtime, they also serve a secondary purpose by acting as markers that the <code>genstrings</code> tool can use to locate your application’s string resources. It is this second purpose that explains why many of the macros let you specify much more information than would normally be required for loading a string. The <code>genstrings</code> tool uses the information you provide to create or update your application’s strings files automatically. <span class="content_text">Table 2-1</span> lists the types of information you can specify for these routines and describes how that information is used by the <code>genstrings</code> tool. </p><a name="http://apple_ref/doc/uid/10000051i-CH6-SW3" title="Table 2-1Common parameters found in string-loading routines"></a><div class="tableholder"><table class="graybox" border = "0" cellspacing="0" cellpadding="5"><caption class="tablecaption"><strong class="caption_number">Table 2-1</strong> Common parameters found in string-loading routines</caption><tr><th scope="col" class="TableHeading_TableRow_TableCell"><p>Parameter</p></th><th scope="col" class="TableHeading_TableRow_TableCell"><p>Description</p></th></tr><tr><td scope="row"><p>Key</p></td><td ><p>The string used to look up the corresponding value. This string must not contain any characters from the extended ASCII character set, which includes accented versions of ASCII characters. If you want the initial value string to contain extended ASCII characters, use a routine that lets you specify a default value parameter. (For information about the extended ASCII character set, see the corresponding <span class="content_text"><a class="urlLink" rel="external">Wikipedia entry</a></span>.) </p></td></tr><tr><td scope="row"><p>Table name</p></td><td ><p>The name of the strings file in which the specified key is located. The <code>genstrings</code> tool interprets this parameter as the name of the strings file in which the string should be placed. If no table name is provided, the string is placed in the default <code>Localizable.strings</code> file. (When specifying a value for this parameter, include the filename without the <code>.strings</code> extension.)</p><p>A <code>.strings</code> file whose table name ends with <code>.nocache</code>—for example <code>ErrorNames.nocache.strings</code>—will not have its contents cached by <code><a target="_self" class="urlLink">NSBundle</a></code>.</p></td></tr><tr><td scope="row"><p>Default value</p></td><td ><p>The default value to associate with a given key. If no default value is specified, the <code>genstrings</code> tool uses the key string as the initial value. Default value strings may contain extended ASCII characters. </p></td></tr><tr><td scope="row"><p>Comment</p></td><td ><p>Translation comments to include with the string. You can use comments to provide clues to the translation team about how a given string is used. The <code>genstrings</code> tool puts these comments in the strings file and encloses them in C-style comment delimiters (<code>/*</code> and <code>*/</code>) immediately above the associated entry. </p></td></tr><tr><td scope="row"><p>Bundle</p></td><td ><p>An <code><a target="_self" class="urlLink">NSBundle</a></code> object or <code><a target="_self" class="urlLink">CFBundleRef</a></code> type corresponding to the bundle containing the strings file. You can use this to load strings from bundles other than your application’s main bundle. For example, you might use this to load localized strings from a <span class="pediaLink" data-header="Framework" data-contents="A framework is a bundle (a structured directory) that contains a dynamic shared library along with associated resources, such as nib files, image files, and header files. "><a href="../../../../General/Conceptual/DevPedia-CocoaCore/Framework.html#//apple_ref/doc/uid/TP40008195-CH56" data-renderer-version="1" target="_self">framework</a></span> or plug-in.</p></td></tr></table></div><p>When you request a string from a strings file, the string that is returned depends on the available localizations (if any). The Cocoa and Core Foundation macros use the built-in <span class="pediaLink" data-header="Bundle" data-contents="A bundle is a directory in the file system that groups executable code and related resources such as images and sounds together in one place. "><a href="../../../../General/Conceptual/DevPedia-CocoaCore/Bundle.html#//apple_ref/doc/uid/TP40008195-CH4" data-renderer-version="1" target="_self">bundle</a></span> internationalization support to retrieve the string whose localization matches the user’s current language preferences. As long as your localized resource files are placed in the appropriate language-specific project directories, loading a string with these macros should yield the appropriate string automatically. If no appropriate localized string resource is found, the bundle’s loading code automatically chooses the appropriate nonlocalized string instead. </p><p>For information about internationalization in general and how to create language-specific project directories, see <em><a href="../../../../MacOSX/Conceptual/BPInternational/Introduction/Introduction.html#//apple_ref/doc/uid/10000171i" data-renderer-version="1" target="_self">Internationalization and Localization Guide</a></em>. For information about the bundle structure and how resource files are chosen from a bundle directory, see <em><a href="../../../../CoreFoundation/Conceptual/CFBundles/Introduction/Introduction.html#//apple_ref/doc/uid/10000123i" data-renderer-version="1" target="_self">Bundle Programming Guide</a></em>.</p><section><a name="http://apple_ref/doc/uid/10000051i-CH6-98108" title="Using the Core Foundation Framework"></a><h3 class="jump">Using the Core Foundation Framework</h3><p>The Core Foundation framework defines a single function and several macros for loading localized strings from your application bundle. The <code><a href=
-
小結(jié)
- 通過讀取
url的內(nèi)容
钢拧,并使用響應(yīng)的編碼方式(一般為UTF-8
)轉(zhuǎn)化為字符串 - 如果
url
內(nèi)容加載失敗蟹漓,或者編碼方式錯誤,初始化失敗源内,返回nil
- 通過讀取
通過本地文件
file
-
方法
//使用指定的編碼方式 - (nullable instancetype)initWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error; + (nullable instancetype)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error; - (nullable instancetype)initWithContentsOfFile:(NSString *)path usedEncoding:(nullable NSStringEncoding *)enc error:(NSError **)error; + (nullable instancetype)stringWithContentsOfFile:(NSString *)path usedEncoding:(nullable NSStringEncoding *)enc error:(NSError **)error; // 把字符串保存到文件中的方法為 - (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile encoding:(NSStringEncoding)enc error:(NSError **)error;
-
例子
[//one.text](//one.text) 文件內(nèi)容為 hello world! NSError *error = nil; NSString *filePath = [[NSBundle mainBundle] pathForResource:@"one.text" ofType:nil]; NSString *str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error]; if (!error) { NSLog(@"成功---"); NSLog(@"%@", str); } else { NSLog(@"失敗---"); } //輸出: 成功--- hello world!
-
小結(jié)
- 讀取本地文件
file
內(nèi)容葡粒,并按照響應(yīng)的編碼方式(一般為UTF-8
)轉(zhuǎn)化為字符串 - 如果
file
內(nèi)容加載失敗,或者編碼方式錯誤,初始化失敗嗽交,返回nil
- 讀取本地文件
Java new String
初始化一個
空
的字符串""
String str = "";
通過字符串
String
-
方法
public String(String original) { }
-
例子
String str = new String("hello"); Log.d("字符串", str); //輸出: hello
-
小結(jié)
-
如果是通過一個
字符串常量
初始化卿嘲,則不推薦使用上面方法,直接復制即可轮纫,如下String str = "hello";
-
通過字符
char
UTF-16 code units
-
方法
//字符數(shù)組 public String(char[] value) { } /** * value - 作為字符源的數(shù)組腔寡。 offset - 初始偏移量。 count - 長度掌唾。 */ //從字符源數(shù)組value的offset索引位置處連續(xù)取出count長度的的子數(shù)組構(gòu)建字符串 //如果 offset 和 count 參數(shù)索引字符超出 value 數(shù)組的范圍放前,則會拋出異常 IndexOutOfBoundsException public String(char[] value, int offset, int count)
-
例子
char[] chars = new char[3]; chars[0] = 'h'; chars[1] = 'e'; chars[2] = '無'; String str = new String(chars); Log.d("字符串", str); //輸出: he無 //從字符源數(shù)組value的offset索引位置處連續(xù)取出count長度的的子數(shù)組構(gòu)建字符串 char [] chars = new char[3]; chars[0] = 'h'; chars[1] = 'e'; chars[2] = '無'; String str = new String(chars, 1, 2); Log.d("字符串", str); //輸出: e無
-
小結(jié)
-
java
字符串用雙引號""
(String
),字符用單引號''
(char
) - 字符串
String
是由字符char
作為單元構(gòu)成的糯彬,char
作為java
中字符串的基本單元code unit
-
通過
unicode
points
代碼點
-
方法
/* * codePoints - 作為 Unicode 代碼點的源的數(shù)組凭语。 offset - 初始偏移量。 count - 長度撩扒。 */ //從Unicode代碼點的源的數(shù)組codePoints的offset索引位置處連續(xù)取出count長度的的子數(shù)組構(gòu)建字符串 //如果 offset 和 count 參數(shù)索引字符超出 value 數(shù)組的范圍似扔,則會拋出異常 IndexOutOfBoundsException //如果在 codePoints 中發(fā)現(xiàn)任何無效的 Unicode 代碼點,則會拋出異常 IllegalArgumentException public String(int[] codePoints, int offset, int count)
-
例子
int[] points = new int[2]; points[0] = 104; points[1] = 101; String str = new String(points, 0, 2); Log.d("字符串", str); //輸出: he
-
小結(jié)
-
codePoints
是字符串單元對應(yīng)的十進制
數(shù)字搓谆,104
對應(yīng)h
炒辉,101
對應(yīng)e
-
code point
先轉(zhuǎn)換為字符char
,char
再轉(zhuǎn)化為字符串String
泉手,即code point
—>char
—>String
-
通過字符集
bytes
Charset
-
方法
//從字節(jié)源數(shù)組bytes的offset索引位置處開始黔寇,截取length長度的子數(shù)組,并將子數(shù)組按照響應(yīng)的解碼方法解碼斩萌,構(gòu)建字符串 // - 如果指定的字符集不受支持 缝裤,拋出異常UnsupportedEncodingException // - 如果 offset 和 length 參數(shù)索引字符超出 bytes 數(shù)組的范圍 , 拋出異常IndexOutOfBoundsException /** * bytes - 要解碼為字符的 byte offset - 要解碼的第一個 byte 的索引 length - 要解碼的 byte 數(shù) charsetName - 受支持 charset 的名稱 */ public String(byte[] bytes, int offset, int length, String charsetName) throws UnsupportedEncodingException /** * bytes - 要解碼為字符的 byte offset - 要解碼的第一個 byte 的索引 length - 要解碼的 byte 數(shù) charset - 用來解碼 bytes 的 charset */ public String(byte[] bytes, int offset, int length, Charset charset) /** * bytes - 要解碼為字符的 byte charsetName - 受支持的 charset 的名稱 */ public String(byte[] bytes, String charsetName) throws UnsupportedEncodingException /** * bytes - 要解碼為字符的 byte charset - 要用來解碼 bytes 的 charset */ public String(byte[] bytes, Charset charset) /** * bytes - 要解碼為字符的 byte offset - 要解碼的第一個 byte 的索引 length - 要解碼的 byte 數(shù) */ public String(byte[] bytes, int offset, int length) /** * bytes - 要解碼為字符的 byte */ public String(byte[] bytes)
-
例子
String string = "hello 世界 world"; byte[] bytes = string.getBytes(); //默認是UTF-8編碼 String str = new String(bytes); Log.d("字符串", str); String UTF8Str = new String(bytes, Charset.forName("UTF-8")); Log.d("字符串", UTF8Str); try { String gbkStr = new String(bytes, "GBK"); Log.d("字符串", gbkStr); } catch (UnsupportedEncodingException e) { Log.d("字符串", "error-----"); } String strOffset = new String(bytes, 1, 2); String UTF8StrOffset = new String(bytes, 1, 2, Charset.forName("UTF-8")); String gbkStrOffset = new String(bytes, 1, 2, Charset.forName("GBK")); Log.d("字符串", strOffset); Log.d("字符串", UTF8StrOffset); Log.d("字符串", gbkStrOffset); //輸出: hello 世界 world hello 世界 world hello 涓栫晫 world el el el
-
小結(jié)
- 通過使用指定的
字符集 解碼
指定的byte 子數(shù)組
颊郎,構(gòu)造一個新的String
- 編碼方式和解碼方式不一致時憋飞,會導致顯示異常,有可能會出現(xiàn)亂碼姆吭,如
UTF-8
編碼榛做,GBK
解碼
- 通過使用指定的
JS String.from
通過
UTF-16 code units
-
方法
//有序的UTF-16 code units編碼單元構(gòu)建,有效范圍時是0 and 65535猾编,超過范圍的會被截斷瘤睹,舍棄 String.fromCharCode(num1[, ...[, numN]])
-
例子
console.log(String.fromCharCode(65, 66, 67)) console.log(String.fromCharCode(0x2014)) console.log(String.fromCharCode(0x12014)) console.log(String.fromCharCode(8212)) console.log(String.fromCharCode(65, 66, 67, 0x2014)) //輸出: ABC — — — ABC—
-
小結(jié)
- 可以直接使用
UTF-16 code units
對應(yīng)的十進制
數(shù)字,(65
,66
,67
) - 可以直接使用
UTF-16 code units
對應(yīng)的十六進制
數(shù)字答倡,十六進制0x2014
對應(yīng)十進制為8212
轰传,輸出結(jié)果都為:—
- 也可以
組合使用
,只要填入的內(nèi)容可以轉(zhuǎn)化為數(shù)字
瘪撇,并且在0~65535
范圍內(nèi)就行 - 因為使用的是
16
位2進制
获茬,即4
位16進制
港庄,所以范圍為0~65535
- 可以直接使用
通過
code points
-
方法
//有序的code points String.fromCodePoint(num1[, ...[, numN]])
-
例子
console.log(String.fromCodePoint(42)) console.log(String.fromCodePoint(65, 90)) console.log(String.fromCodePoint(0x404)) console.log(String.fromCodePoint(1028)) console.log(String.fromCodePoint(0x2F804)) console.log(String.fromCodePoint(194564)) //輸出: * AZ ? ? ? ?
-
小結(jié)
- 通過
code point
構(gòu)建字符串,沒有范圍0~65535
的限制 - 通過
code point
構(gòu)建字符串恕曲,可以使用16進制
鹏氧,也可以使用10進制
,如?的16
進制0x404
轉(zhuǎn)化為10
進制為1028
佩谣,輸出結(jié)果都為?
把还;16
進制0x2F804
轉(zhuǎn)化為10
進制為194564
,輸出結(jié)果都為?茸俭,
但是不可以使用字符常量吊履,如'+'
,會報錯
- 通過
小結(jié)
不同點
-
oc
中字符串寫法@""
调鬓,java
中字符串寫法""
艇炎,js
中字符串寫法""
和''
都可以,一個字符@
的區(qū)別 -
char
基本數(shù)據(jù)類型腾窝,oc
中表示1
個字節(jié)缀踪、java
表示2
個字節(jié) -
byte
在java
中表示一
個字節(jié),oc
也是一
個字節(jié)虹脯,oc
為Byte
-
unicode
編碼需要用2
個字節(jié)表示驴娃,oc
中用unichar
表示,java
用char
-
java
字符串的構(gòu)建關(guān)系:code point
—>char
—>String
相同點
-
通過字符串常量初始化的時候循集,推薦直接賦值
[//oc](//oc) NSString *str = @"one"; //java String str = "hello"; //js var str = "hello world"
code point —> code unit —> string
-
字符串的
長度
托慨,范圍
等處理都是都以unicode unit
為基礎(chǔ)的,即組成該字符串所需要的unicode unit
數(shù)目暇榴,即需要多少了2字節(jié)
存儲,oc
用unichar
蕉世,java
用char
蔼紧,//oc NSString *string = @"hello 世界 world"; NSLog(@"%ld", string.length); //輸出: 14 //java String string = "hello 世界 world"; Log.d("字符串", String.valueOf(string.length())); //輸出: 14 //js var str = "hello 世界 world"; console.log(str.length) //輸出: 14
-
字符串
常量
//oc NSString *str = @"one"; //java String str = "hello"; //js var str = "hello 世界 world";
把字符串源(字節(jié)
bytes
,字符char
狠轻,unicode units
)按照指定的編碼方式進行解碼奸例,
-java
:char
、bytes
向楼;unicode points
查吊、
-oc
:characters
、bytes
湖蜕;NSData
逻卖、CString
、NSURL
昭抒、file
-js
:CharCode
评也、CodePoint
-
通過
unicode
字符構(gòu)建字符串-
oc
:initWithCharacters
炼杖,可以使用十六進制(如0x2b)
、十進制數(shù)字(如43)
盗迟、字符常量(如'+')
// 43 坤邪、0x2b 、'+' 這些輸出的都是 + const unichar ch = 43; NSString *str = [[NSString alloc] initWithCharacters:&ch length:3]; NSLog(@"%@", str); //輸出: + unichar ch[3]; ch[0] = '+'; ch[1] = 43; ch[2] = 0x2b; NSString *str = [[NSString alloc] initWithCharacters:ch length:sizeof(ch) / sizeof(unichar)]; NSLog(@"%@", str); //輸出: +++
-
java
:public String(char[] value)
罚缕、public String(int[] codePoints, int offset, int count)
艇纺,可以使用十六進制(如0x2b)
、十進制數(shù)字(如43)
邮弹、字符常量(如'+')
char [] chars = new char[3]; chars[0] = '+'; chars[1] = 43; chars[2] = 0x2b; String str = new String(chars); Log.e("字符串", str); // 輸出: E/字符串: +++ int[] points = new int[3]; points[0] = '+'; points[1] = 43; points[2] = 0x2b; String str = new String(points, 0, 3); Log.e("字符串", str); // 輸出: E/字符串: +++
-
js
:String.fromCodePoint
黔衡、String.fromCharCode
,可以使用十六進制(0x2b)
肠鲫,十進制數(shù)字(如43)
员帮,不可以
使用字符常量(如'+')
,String.fromCodePoint
會報錯(RangeError: Invalid code point NaN
)导饲,String.fromCharCode
會輸出空字符console.log(String.fromCodePoint(0x2b)); console.log(String.fromCodePoint(43)); // console.log(String.fromCodePoint('+')); // 會拋出異常 RangeError: Invalid code point NaN console.log(String.fromCharCode('+')); // console.log("-------"); //輸出: + + -------
-
二捞高、長度 length
-
OC
length
length
NSString *str = @"one"; NSLog(@"%ld", str.length); //輸出:3
-
Java
length()
length()
String str = "one"; Log.d("length", String.valueOf(str.length())); //輸出:3
-
JS
length
length
var str = "one"; console.log(str.length) //輸出:3
-
小結(jié)
關(guān)鍵字都是
length
三、比較 compare
基本概念
-
字典排序
: 按字典順序比較兩個字符串渣锦。該比較基于字符串中各個字符的Unicode
值硝岗。按字典順序?qū)⒋?String 對象表示的字符序列與參數(shù)字符串所表示的字符序列
進行比較。如果按字典順序此String
對象位于參數(shù)字符串之前
袋毙,則比較結(jié)果為一個負整數(shù)
型檀。如果按字典順序此 String 對象位于參數(shù)字符串之后
,則比較結(jié)果為一個正整數(shù)
听盖。如果這兩個字符串相等
胀溺,則結(jié)果為0
;
OC equal
皆看、compare
-
方法
//相等判斷 - (BOOL)isEqualToString:(NSString *)aString; //按照unicode編碼順序比較仓坞、相等:NSOrderedSame,在前面NSOrderedAscending腰吟,在后面NSOrderedDescending - (NSComparisonResult)compare:(NSString *)string; //忽略大小寫進行比較无埃、'A'和'a'相等 - (NSComparisonResult)caseInsensitiveCompare:(NSString *)string; //比較大小,根據(jù)傳入的mask參數(shù) - (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask; //截取調(diào)用者range范圍的子字符串和參數(shù)string進行比較 - (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToCompare; //本地化的處理 @ - (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToCompare locale:(nullable id)locale; - (NSComparisonResult)localizedCompare:(NSString *)string; - (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)string; - (NSComparisonResult)localizedStandardCompare:(NSString *)string API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0)); //比較結(jié)果如下: typedef NS_ENUM(NSInteger, NSComparisonResult) { NSOrderedAscending = -1L, NSOrderedSame, NSOrderedDescending }; //mask選項如下: /* These options apply to the various search/find and comparison methods (except where noted). */ typedef NS_OPTIONS(NSUInteger, NSStringCompareOptions) { NSCaseInsensitiveSearch = 1, NSLiteralSearch = 2, /* Exact character-by-character equivalence */ NSBackwardsSearch = 4, /* Search from end of source string */ NSAnchoredSearch = 8, /* Search is limited to start (or end, if NSBackwardsSearch) of source string */ NSNumericSearch = 64, /* Added in 10.2; Numbers within strings are compared using numeric value, that is, Foo2.txt < Foo7.txt < Foo25.txt; only applies to compare methods, not find */ NSDiacriticInsensitiveSearch API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)) = 128, /* If specified, ignores diacritics (o-umlaut == o) */ NSWidthInsensitiveSearch API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)) = 256, /* If specified, ignores width differences ('a' == UFF41) */ NSForcedOrderingSearch API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)) = 512, /* If specified, comparisons are forced to return either NSOrderedAscending or NSOrderedDescending if the strings are equivalent but not strictly equal, for stability when sorting (e.g. "aaa" > "AAA" with NSCaseInsensitiveSearch specified) */ NSRegularExpressionSearch API_AVAILABLE(macos(10.7), ios(3.2), watchos(2.0), tvos(9.0)) = 1024 /* Applies to rangeOfString:..., stringByReplacingOccurrencesOfString:..., and replaceOccurrencesOfString:... methods only; the search string is treated as an ICU-compatible regular expression; if set, no other options can apply except NSCaseInsensitiveSearch and NSAnchoredSearch */ };
-
例子
NSString *str1 = @"A"; NSString *str2 = @"a"; NSComparisonResult result = [str1 compare:str2]; if (result == NSOrderedSame) { NSLog(@"比較:相等"); } else if (result == NSOrderedAscending) { NSLog(@"比較:位于前面"); } else { NSLog(@"比較:位于后面"); } //打印結(jié)果: 比較:位于前面 NSString *str1 = @"aA"; NSString *str2 = @"a"; NSComparisonResult result = [str1 compare:str2]; if (result == NSOrderedSame) { NSLog(@"比較:相等"); } else if (result == NSOrderedAscending) { NSLog(@"比較:位于前面"); } else { NSLog(@"比較:位于后面"); } //輸出: 比較:位于后面
小結(jié)
- 根據(jù)mask
傳入的參數(shù)不同毛雇,獲取的結(jié)果不一樣嫉称;如mask
傳入NSCaseInsensitiveSearch
,等價于caseInsensitiveCompare:
- 比較只返回比較結(jié)果灵疮,不會返回差值
Java equal
昼牛、compare
-
方法
//字典順序比較大小 public int compareTo(String anotherString) //忽略大小寫進行比較 public int compareToIgnoreCase(String str) //相等判斷拯田,類型也要相同仪壮,為String類 public boolean equals(Object anObject) { } //相等判斷,忽略大小寫氮趋,'A'和'a'相等 public boolean equalsIgnoreCase(String anotherString) { } //相等判斷,內(nèi)容相等江耀,類型可能不相同 public boolean contentEquals(StringBuffer sb) { } public boolean contentEquals(CharSequence cs) { }
-
例子
//相同長度剩胁,某個位置處字符不同 String str1 = "A"; String str2 = "a"; int result = str1.compareTo(str2); Log.d("差值:", String.valueOf(result)); if (result == 0) { Log.d("排序:", "相等"); } else if (result < 0) { Log.d("排序:", "位于前面"); } else { Log.d("排序:", "位于后面"); } //輸出: -32 位于前面 //長度不同的比較 String str1 = "aA"; String str2 = "a"; int result = str1.compareTo(str2); Log.d("差值:", String.valueOf(result)); if (result == 0) { Log.d("排序:", "相等"); } else if (result < 0) { Log.d("排序:", "位于前面"); } else { Log.d("排序:", "位于后面"); } //輸出: 1 位于后面 //索引位置處字符不同,長度不同 String str1 = "Aa"; String str2 = "a"; int result = str1.compareTo(str2); Log.d("差值:", String.valueOf(result)); if (result == 0) { Log.d("排序:", "相等"); } else if (result < 0) { Log.d("排序:", "位于前面"); } else { Log.d("排序:", "位于后面"); } //輸出: -32 位于前面 //忽略大小寫的比較 String str1 = "A"; String str2 = "a"; int result = str1.compareToIgnoreCase(str2); Log.d("差值:", String.valueOf(result)); if (result == 0) { Log.d("排序:", "相等"); } else if (result < 0) { Log.d("排序:", "位于前面"); } else { Log.d("排序:", "位于后面"); } //輸出: 0 相等
小結(jié)
- 字符串不同的情況:1祥国、相同索引
處的unicode units不同
昵观;2、長度
不同舌稀;3啊犬、
1和2都有
- 比較的優(yōu)先級:優(yōu)先比較1
的情況,然后在比較2
的情況
- 對于1
的情況壁查,返回的unicode units
的差值
觉至,this.charAt(k)-anotherString.charAt(k)
- 對于2
的情況,返回的是長度差值
睡腿,this.length()-anotherString.length()
JS compare
-
方法
/** referenceStr在compareString“前面”语御,返回“負值”,不一定是-1席怪,不同瀏覽器返回“負值”不同应闯,但是都是“負值” referenceStr在compareString“后面”,返回“正值”挂捻,不一定是1碉纺,不同瀏覽器返回“正值”不同,但是都是“正值” referenceStr在compareString“相同位置”刻撒,返回0 */ referenceStr.localeCompare(compareString[, locales[, options]])
-
例子
//字符不同 var str1 = "A" var str2 = "Z" var result = str1.localeCompare(str2) console.log(result) if (result == 0) { console.log("比較:", "相等"); } else if (result < 0) { console.log("比較:", "位于前面"); } else { console.log("比較:", "位于后面"); } //輸出: -1 比較: 位于前面 //長度不同 var str1 = "AZ" var str2 = "A" var result = str1.localeCompare(str2) console.log(result) if (result == 0) { console.log("比較:", "相等"); } else if (result < 0) { console.log("比較:", "位于前面"); } else { console.log("比較:", "位于后面"); } //輸出: 1 位于后面
小結(jié)
- 比較只返回比較結(jié)果骨田,不會返回差值
小結(jié)
相同點
- 小于:返回負值
- 相等:返回0
- 大于:返回正值
-
不同點
-js
和oc
只是單純進行字符串比較,不會返回差值
声怔;但是java會返回差值
(見?)盛撑;oc
對比較結(jié)果進行了封裝,是一個枚舉
類型:typedef NS_ENUM(NSInteger, NSComparisonResult) { NSOrderedAscending = -1L, NSOrderedSame, NSOrderedDescending }; - `oc`和`java`提供了`忽略大小寫`的比較方法捧搞,`js`沒有直接方法,但是可以先全部轉(zhuǎn)為`小寫字母`(`toLowerCase()`)狮荔,然后再進行`比較`(`localeCompare()`)胎撇;
四、前綴/后綴 hasPrefix
殖氏、hasSuffix
晚树、startsWith
、 endsWith
OC hasPrefix
雅采、hasSuffix
-
方法
// 前綴 - (BOOL)hasPrefix:(NSString *)str; // 后綴 - (BOOL)hasSuffix:(NSString *)str; // 獲取相同的前綴 - (NSString *)commonPrefixWithString:(NSString *)str options:(NSStringCompareOptions)mask;
-
例子
NSString *str = @"hello world"; if ([str hasPrefix:@"hello"]) { NSLog(@"包含前綴:hello"); } else { NSLog(@"不包含前綴:hello"); } if ([str hasPrefix:@"world"]) { NSLog(@"包含前綴:world"); } else { NSLog(@"不包含前綴:world"); } if ([str hasSuffix:@"hello"]) { NSLog(@"包含后綴:hello"); } else { NSLog(@"不包含后綴:hello"); } if ([str hasSuffix:@"world"]) { NSLog(@"包含后綴:world"); } else { NSLog(@"不包含后綴:world"); } // 輸出: 包含前綴:hello 不包含前綴:world 不包含后綴:hello 包含后綴:world NSString *str = @"onetwothreeonetwo"; NSString *searchStr = @"oneuoptwo"; NSString *commonPrefix = [str commonPrefixWithString:searchStr options:0]; NSLog(@"%@", commonPrefix); // 輸出: one
小結(jié)
Java startsWith
爵憎、 endsWith
-
方法
// 前綴 public boolean startsWith(String prefix) // 如果參數(shù)表示的字符序列是此對象從索引 toffset 處開始的子字符串前綴慨亲,則返回 true;否則返回 false宝鼓。如果 toffset 為負或大于此 String 對象的長度刑棵,則結(jié)果為 false;否則結(jié)果與以下表達式的結(jié)果相同: public boolean startsWith(String prefix, int toffset) //后綴 public boolean endsWith(String suffix)
-
例子
String str = "hello world"; if (str.startsWith("hello")) { Log.e("前綴判斷", "包含前綴:hello"); } else { Log.e("前綴判斷", "不包含前綴:hello"); } if (str.startsWith("world")) { Log.e("前綴判斷", "包含前綴:world"); } else { Log.e("前綴判斷", "不包含前綴:world"); } if (str.endsWith("hello")) { Log.e("后綴判斷", "包含后綴:hello"); } else { Log.e("后綴判斷", "不包含后綴:hello"); } if (str.endsWith("world")) { Log.e("后綴判斷", "包含后綴:world"); } else { Log.e("后綴判斷", "不包含后綴:world"); } // 輸出: E/前綴判斷: 包含前綴:hello E/前綴判斷: 不包含前綴:world E/后綴判斷: 不包含后綴:hello E/后綴判斷: 包含后綴:world
小結(jié)
JS startsWith
愚铡、 endsWith
-
方法
/** * “源字符串”的 position 位置(包含)之后的子字符串 是否是以 searchString 開頭的 * 1蛉签、position 表示在 源字符串str 中搜索 searchString 的 “開始位置”,默認值為 0沥寥,也就是真正的字符串開頭處 */ str.startsWith(searchString [, position]); /** * “源字符串”的 position 位置(不包含)之后的子字符串 是否是以 searchString 結(jié)尾的 * 1碍舍、position 表示在 源字符串str 中搜索 searchString 的結(jié)束位置,默認值為 str.length邑雅,也就是真正的字符串結(jié)尾處片橡。 */ str.endsWith(searchString [, position]);
-
例子
//前綴 var str = 'hello world'; console.log(str.startsWith('hello')); console.log(str.startsWith('hello', 5)); console.log(str.startsWith('world')); console.log(str.startsWith('world', 6)); console.log(str.startsWith('hello', 20)); //輸出: true false false true false //后綴 var str = 'hello world'; console.log(str.endsWith('world')); console.log(str.endsWith('world', 5)); console.log(str.endsWith('hello')); console.log(str.endsWith('hello', 4)); console.log(str.endsWith('hello', 5)); console.log(str.endsWith('hello', 6)); //輸出: true false false false true false
小結(jié)
-startsWith
前綴判斷,“源字符串”position
(包含
) 到length - 1
范圍內(nèi)的字符串是不是以searchString
開頭的
-endsWith
后綴判斷淮野,“源字符串”0
到position
(不包含
) 范圍內(nèi)的字符串是不是以searchString
結(jié)尾的
- 先從 “源字符串” 獲取判斷的字符串范圍捧书,然后再進行判斷
小結(jié)
-
Java
和JS
的關(guān)鍵字為startsWith
、endsWith
录煤,OC
為hasPrefix
鳄厌、hasSuffix
五、包含 contains
妈踊、includes
OC contains
-
方法
//包含 - (BOOL)containsString:(NSString *)str API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); - (BOOL)localizedCaseInsensitiveContainsString:(NSString *)str API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); - (BOOL)localizedStandardContainsString:(NSString *)str API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); - (NSRange)localizedStandardRangeOfString:(NSString *)str API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0));
-
例子
NSString *str = @"oneTwo"; NSString *searchStr = @"ONE"; BOOL result = [str containsString:searchStr]; BOOL result2 = [str localizedCaseInsensitiveContainsString:searchStr]; NSLog(@"%@", @(result)); NSLog(@"%@", @(result2)); // 輸出: 0 為 NO了嚎,1為YES 0 1
小結(jié)
Java contains
-
方法
public boolean contains(CharSequence s)
-
例子
String str = "hello world"; boolean result = str.contains("hello"); boolean result2 = str.contains("me"); Log.e("包含", String.valueOf(result)); Log.e("包含", String.valueOf(result2)); // 輸出: E/包含: true E/包含: false
小結(jié)
JS includes
-
方法
/* * 判斷一個字符串是否包含在另一個字符串中,根據(jù)情況返回true或false廊营。 */ str.includes(searchString[, position])
-
例子
var str = 'hello world'; var result = str.includes('hello'); var result2 = str.includes('me'); console.log(result); console.log(result2); //輸出: true false
小結(jié)
六歪泳、拼接/插入 append
、insert
露筒、concat
基本概念
-
oc
中的字符串類 -
NSString
: 不可變的 -
NSMutableString
:可變的 -
Java
的字符串類: -
String
: 不可變呐伞; -
StringBuilder
:可變的,線程不安全
-
StringBuffer
:可變的慎式,線程安全
- 小結(jié):
StringBuilder
比StringBuffer
快伶氢,優(yōu)先使用StringBuilder
OC append
、insert
瘪吏、padding
-
方法
//不可變字符串的處理----------- //把字符串a(chǎn)String拼接“源字符串”的"末尾" - (NSString *)stringByAppendingString:(NSString *)aString; //把字符串a(chǎn)String拼接“源字符串”的"末尾"癣防,帶有格式的拼接 - (NSString *)stringByAppendingFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2); //在“源字符串”的末尾位置處拼接字符串“padString”,從使padString的padIndex所有位置處開始拼接掌眠,使“源字符串”的長度為newLength /* * newLength : 源字符串需要擴展到的長度 大于原來長度蕾盯,末尾插入 等于原來長度,不做處理 小于原來長度蓝丙,截取處理 padString : 需要拼接的子字符串 padIndex : 需要拼接的子字符串padString開始拼接的位置(僅僅是第一次)级遭,超過范圍會crash */ - (NSString *)stringByPaddingToLength:(NSUInteger)newLength withString:(NSString *)padString startingAtIndex:(NSUInteger)padIndex; //可變字符串的處理----------- //源字符串“末尾”拼接字符串a(chǎn)String - (void)appendString:(NSString *)aString; //源字符串“末尾”按照格式拼接字符串 - (void)appendFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2); //源字符串loc位置處插入字符串a(chǎn)String - (void)insertString:(NSString *)aString atIndex:(NSUInteger)loc;
-
例子
NSString *str = @"one"; NSString *str2 = [str stringByAppendingString:@"two"]; NSString *str3 = [str stringByAppendingFormat:@"%@ hello %d", str2, 3]; NSLog(@"%@", str2); NSLog(@"%@", str3); //輸出: onetwo oneonetwo hello 3 NSString *str = @"one"; NSString *result = [str stringByPaddingToLength:10 withString:@"+" startingAtIndex:0]; NSLog(@"%@", result); NSLog(@"%ld", result.length); //輸出: str length string index result result.length one 10 + 0 one+++++++ 10 one 3 + 0 one 3 one 2 + 0 on 2 one 0 + 0 0 one 0 + 1 crash了 one 6 +- 1 one-+- 6 NSMutableString *str = [NSMutableString string]; NSLog(@"%@", str); [str appendString:@"two"]; NSLog(@"%@", str); [str appendFormat:@"hello %d", 3]; NSLog(@"%@", str); [str insertString:@"first " atIndex:0]; NSLog(@"%@", str); //輸出: two twohello 3 first twohello 3
小結(jié)
-NSString
不會改變原來字符串的值望拖,會返回一個新的值
-NSMutableString
是對原來字符串進行處理,不會返回新值
Java concat
挫鸽、format
说敏、append
、insert
-
方法
//將指定字符串str拼接到“源字符串”的結(jié)尾 public String concat(String str) //類方法掠兄,格式化拼接字符串 public static String format(String format, Object... args) //類方法像云,格式化拼接字符串,本地化的 public static String format(Locale l, String format, Object... args) //append ----- public StringBuilder append(Object obj) public StringBuilder append(String str) public StringBuilder append(StringBuffer sb) public StringBuilder append(CharSequence s) public StringBuilder append(CharSequence s, int start, int end) public StringBuilder append(char[] str) public StringBuilder append(char[] str, int offset, int len) public StringBuilder append(boolean b) public StringBuilder append(char c) public StringBuilder append(int i) public StringBuilder append(long lng) public StringBuilder append(float f) public StringBuilder append(double d) public StringBuilder appendCodePoint(int codePoint) //insert public StringBuilder insert(int offset, boolean b) public StringBuilder insert(int offset, char c) public StringBuilder insert(int offset, int i) public StringBuilder insert(int offset, long l) public StringBuilder insert(int offset, float f) public StringBuilder insert(int offset, double d)
-
例子
String str = "one"; String result = str.concat("two"); Log.d("字符串拼接", result); //輸出: onetwo String str = "one"; String result = String.format("%s %s %d", str, "two", 10); Log.d("字符串拼接", result); //輸出: one two 10 [//append---](//append---) StringBuilder sb = new StringBuilder(); Log.d("字符串拼接:開始:", sb.toString()); sb.append("str"); Log.d("字符串拼接:拼接string之后:", sb.toString()); String nullStr = null; sb.append(" "); sb.append(nullStr); Log.d("字符串拼接:拼接空string之后:", sb.toString()); StringBuilder sb2 = new StringBuilder("sb"); sb.append(" "); sb.append(sb2); Log.d("拼接StringBuilder之后:", sb.toString()); StringBuffer sf = new StringBuffer("sf"); sb.append(" "); sb.append(sf); Log.d("拼接StringBuffer之后:", sb.toString()); char[] chars = new char[2]; chars[0] = 'a'; chars[1] = 'b'; sb.append(" "); sb.append(chars); Log.d("拼接char[]之后:", sb.toString()); sb.append(" "); sb.append(true); Log.d("字符串拼接:拼接boolean之后:", sb.toString()); sb.append(" "); sb.append('a'); Log.d("字符串拼接:拼接char之后:", sb.toString()); sb.append(" "); sb.append(10); Log.d("字符串拼接:拼接int之后:", sb.toString()); sb.append(" "); sb.append(100L); Log.d("字符串拼接:拼接long之后:", sb.toString()); sb.append(" "); sb.append(20.32f); Log.d("字符串拼接:拼接float之后:", sb.toString()); sb.append(" "); sb.append(50.5); Log.d("字符串拼接:拼接double之后:", sb.toString()); sb.append(" "); sb.appendCodePoint(104); Log.d("字符串拼接:拼接codePoint之后:", sb.toString()); //最終輸出: str null sb sf ab true a 10 100 20.32 50.5 h //insert--- 參考`append`
小結(jié)
-append
和insert
可以看出是format
的便捷方法
- 如果拼接的值為null
蚂夕,則向該序列中追加 4 個 "null
" 字符
-String
類拼接用concat
迅诬,StringBuilder
類和StringBuffer
類用append
和insert
JS +
、concat
婿牍、repeat
-
方法
/** * 使用加號 + 進行拼接 */ + /** * 把 “源字符串” 重復 count 次 得到新的字符串 * 1侈贷、count 范圍為 [0, +∞),超過范圍會拋出異常 RangeError等脂;count 為 0 返回空字符串 '' */ str.repeat(count) /** * 在 “源字符串”的基礎(chǔ)上拼接 字符串 string2 俏蛮、 string3 、 ... stringN */ str.concat(string2, string3[, ..., stringN])
-
例子
var str = ""; str += "one"; console.log(str) //輸出: one //重復次數(shù) var str = 'hello'; var result = str.repeat(2); var result2 = str.repeat(0); // var result3 = str.repeat(-1); console.log(result); console.log(result2); // console.log(result3); console.log("++++++++") //輸出: hellohello ++++++++ var str = 'hello'; var result = str.concat(' ', 'world'); console.log(result); //輸出: hello world
小結(jié)
-js
的字符串拼接使用加號+
即可
-repeat(count)
:count
的范圍為[0, +∞)
上遥,超過范圍會拋出異常搏屑,count
等于0
返回空字符串''
小結(jié)
- 相同點
1.oc
和java
方法的關(guān)鍵字為append
、insert
粉楚,java多了concat
1.oc
和java
都可以通過格式化字符串format
來拼接字符串 - 不同點
1.js
和java
都可以使用加號+
拼接字符串辣恋,oc
不可以
七、刪除 delete
OC delete
-
方法
//刪除“源字符串”range范圍的字符 - (void)deleteCharactersInRange:(NSRange)range;
-
例子
NSMutableString *str = [NSMutableString stringWithString:@"hello"]; [str deleteCharactersInRange:NSMakeRange(1, 2)]; NSLog(@"%@", str); //輸出: hlo
小結(jié)
-NSMutableString
類才有刪除方法
- 范圍range
超過源字符串范圍時模软,會crash
Java delete
-
方法
//刪除start(包含)到end(不包含)范圍內(nèi)的字符 [//end可以>=length伟骨,超過length表示一直刪除到字符串尾部](//end可以>=length,超過length表示一直刪除到字符串尾部) //如果 start 為負燃异、大于 length() 或大于 end携狭,會拋出異常StringIndexOutOfBoundsException public StringBuilder delete(int start, int end) //刪除index位置處的字符,此序列將縮短一個 char回俐。 //注:如果給定索引處的字符是增補字符逛腿,則此方法將不會移除整個字符。如果需要準確處理增補字符仅颇,那么可以通過調(diào)用 Character.charCount(thisSequence.codePointAt(index))(用此序列取代 thisSequence)來確定要移除的 char 數(shù)单默。 public StringBuilder deleteCharAt(int index)
-
例子
StringBuilder sb = new StringBuilder("hello"); sb.delete(1, 3); //刪除el Log.d("字符串刪除:", sb.toString()); //輸出: hlo StringBuilder sb = new StringBuilder("hello"); sb.delete(1, 10); //刪除ello Log.d("字符串刪除:", sb.toString()); //輸出: h //刪除某個位置的字符 StringBuilder sb = new StringBuilder("hello"); sb.deleteCharAt(1); Log.d("字符串刪除:", sb.toString()); //輸出: hllo
小結(jié)
-delete
和deleteCharAt
是StringBuilder
類和StringBuffer
類才有的
-end
可以大于等于字符串length
,大于等于length
會一直刪除掉“源字符串”的末尾
- 如果start
為負灵莲、大于length()
或大于end
,會拋出異常StringIndexOutOfBoundsException
-deleteCharAt
殴俱,準確刪除的話需要調(diào)用Character.charCount(thisSequence.codePointAt(index))
政冻,確定刪除的字符數(shù)
JS
- 參考
替換
小結(jié)
-
相同點
1. 對于含有emoji
字符的字符串枚抵,有可能需要3個字節(jié)才能表示,但是unicode unit
為2個字節(jié)明场,這時候使用常規(guī)的處理會出現(xiàn)問題汽摹,需要準確的判斷字符串:[//oc:](//oc:) - (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)index; - (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)); //java: `Character.charCount(thisSequence.codePointAt(index))`
不同點
八、獲取 char
苦锨、 codePointAt
OC characterAtIndex
-
方法
/** * 獲取 index 位置處的 unicode unit 的數(shù)字表示形式 * 1逼泣、index 超過范圍 [0, length - 1) 會crash ,因為范圍越界了 */ - (unichar)characterAtIndex:(NSUInteger)index;
-
例子
NSString *str = @"hello world!"; unichar ch = [str characterAtIndex:1]; NSLog(@"%d -- %@", ch, [[NSString alloc] initWithCharacters:&ch length:1]); //輸出: 101 -- e //當 index 為 20 時舟舒,crash 了拉庶, Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFConstantString characterAtIndex:]: Range or index out of bounds'
小結(jié)
Java charAt
、codePointAt
-
方法
// 返回指定索引處的 char 值秃励。索引范圍為從 0 到 length() - 1氏仗。序列的第一個 char 值位于索引 0 處,第二個位于索引 1 處夺鲜,依此類推皆尔,這類似于數(shù)組索引;如果 index 參數(shù)為負或小于此字符串的長度币励,會拋出異常 public char charAt(int index) // 返回指定索引處的字符(Unicode 代碼點)慷蠕。索引引用 char 值(Unicode 代碼單元),其范圍從 0 到 length() - 1 public int codePointAt(int index)
-
例子
String str = "hello world!"; char ch = str.charAt(1); Log.e("獲取", String.valueOf(ch)); // 輸出: E/獲取: e String str = "hello world!"; int point = str.codePointAt(1); Log.e("獲取", String.valueOf(point)); // 輸出: E/獲取: 101
小結(jié)
JS charAt
食呻、charCodeAt
流炕、 codePointAt
-
方法
/** * 獲取index位置處的 UTF-16 code unit 的字符串形式 * 1、不填寫參數(shù)搁进,默認獲取 0 位置處的字符 * 2浪感、index 超過 “源字符串” 的范圍,返回空字符串 "" */ character = str.charAt(index) /** * 獲取 index 處 UTF-16 code unit 的 code point 所代表的數(shù)字 * 1饼问、index 超過范圍 返回 NaN */ str.charCodeAt(index) /** * 獲取 index 位置處的 UTF-16 code unit 的 code point 的數(shù)字形式 * 1影兽、如果 index 超過字符串的范圍,返回undefined */ str.codePointAt(pos)
-
例子
var str = "hello world" var character = str.charAt() var character1 = str.charAt(0) var character2 = str.charAt(20) console.log(character) console.log(character1) console.log(character2) console.log("-----") //輸出: h h ----- var str = "hello world" var result = str.charCodeAt(0) var result1 = str.charCodeAt(20) console.log(result) console.log(result1) //輸出: 104 NaN var str = "hello world" var result = str.codePointAt(0) var result1 = str.codePointAt(20) console.log(result) console.log(result1) //輸出: 104 undefined
小結(jié)
小結(jié)
- 可以獲取到
index
位置的字符 莱革、代碼點code point
九峻堰、查找 range
、indexOf
盅视、lastIndexOf
捐名、search
OC range
-
方法
// 查找給定的字符串 ------- // “源字符串” 全部范圍內(nèi)查找 - (NSRange)rangeOfString:(NSString *)searchString; // “源字符串” 全部范圍內(nèi)查找,添加一些條件 - (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask; // “源字符串” rangeOfReceiverToSearch 范圍內(nèi)查找 闹击,范圍超過 字符串 長度會crash - (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToSearch; // 本地化的查找 - (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToSearch locale:(nullable NSLocale *)locale API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)); // 查找給定的字符集合 ------- - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet; - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet options:(NSStringCompareOptions)mask; - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToSearch;
-
例子
NSString *str = @"hello world"; NSLog(@"%@", NSStringFromRange([str rangeOfString:@"hello"])); NSLog(@"%@", NSStringFromRange([str rangeOfString:@"me"])); // 輸出: {0, 5} {9223372036854775807, 0} NSString *str = @"hello world"; NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"l"]; NSLog(@"%@", NSStringFromRange([str rangeOfCharacterFromSet:set])); // 輸出: {2, 1}
小結(jié)
- 如果查找到返回查找到的范圍镶蹋,沒有查找到話range
的length == 0
Java indexOf
、lastIndexOf
-
方法
// 在”源字符串“中查找 字符串str 或者 ch代表的Unicode 代碼點代表的字符 ”第一次“ 出現(xiàn)的位置,如果未出現(xiàn)該字符贺归,則返回 -1 public int indexOf(String str) public int indexOf(String str, int fromIndex) public int indexOf(int ch) public int indexOf(int ch, int fromIndex) // 在”源字符串“中查找 字符串str 或者 ch代表的Unicode 代碼點代表的字符 ”最后一次“ 出現(xiàn)的位置淆两,如果未出現(xiàn)該字符,則返回 -1 public int lastIndexOf(String str) public int lastIndexOf(String str, int fromIndex) public int lastIndexOf(int ch) public int lastIndexOf(int ch, int fromIndex)
-
例子
String str = "hello world"; Log.e("查找", String.valueOf(str.indexOf("l"))); Log.e("查找", String.valueOf(str.indexOf("p"))); Log.e("查找", String.valueOf(str.indexOf("l", 5))); Log.e("查找", String.valueOf(str.indexOf("l", -1))); Log.e("查找", String.valueOf(str.indexOf("l", 20))); // 輸出: E/查找: 2 E/查找: -1 E/查找: 9 E/查找: 2 E/查找: -1
小結(jié)
-indexOf
是按照“從左往右
”的順序查找
-lastIndexOf
是按照“從右往左
”的順序查找
- 查找到則返回所在位置拂酣,沒有查找到則返回-1
JS indexOf
秋冰、lastIndexOf
、search
-
方法
/** * 從源字符串的 fromIndex 位置處按照“從左往右”順序查找 searchValue “第一次”出現(xiàn)的位置 * 1婶熬、 fromIndex 是可選值剑勾,不填寫值默認從 位置0 開始,小于0(<0)也是從 位置0 開始赵颅,超過字符串長度范圍虽另,從length -1 處開始 * 2、查找到則返回所在位置性含,沒有查找到則返回 -1 * 3洲赵、該方法是大小寫敏感的 */ str.indexOf(searchValue[, fromIndex]) /** * 從源字符串的 fromIndex 位置處按照“從右往左”順序查找 searchValue “第一次”出現(xiàn)的位置, * 1商蕴、 fromIndex 是可選值叠萍,不填寫值默認從 位置0 開始,小于0(<0)也是從 位置0 開始绪商,超過字符串長度范圍苛谷,從length -1 處開始 * 2、查找到則返回所在位置格郁,沒有查找到則返回 -1 */ str.lastIndexOf(searchValue[, fromIndex]) /** * 根據(jù)正則表達式查找內(nèi)容 * 1腹殿、查找到則返回所在位置,沒有查找到則返回 -1 */ str.search(regexp) /* * 沒有匹配到返回 null * 匹配到返回匹配的結(jié)果數(shù)組 */ str.match(regexp)
-
例子
//從左往右查找 var str = "hello world" var index = str.indexOf("l") var index2 = str.indexOf("") var index3 = str.indexOf("987") var index4 = str.indexOf("l", 5) var index5 = str.indexOf("l", 20) var index6 = str.indexOf("l", -20) var index7 = str.indexOf("L") console.log(index) console.log(index2) console.log(index3) console.log(index4) console.log(index5) console.log(index6) console.log(index7) //輸出: 2 0 -1 9 -1 2 -1 //從右往左查找 var str = "hello world" var index = str.lastIndexOf("l") var index2 = str.lastIndexOf("") var index3 = str.lastIndexOf("987") var index4 = str.lastIndexOf("l", 5) var index5 = str.lastIndexOf("l", 20) var index6 = str.lastIndexOf("l", -20) var index7 = str.lastIndexOf("L") console.log(index) console.log(index2) console.log(index3) console.log(index4) console.log(index5) console.log(index6) console.log(index7) //輸出: 9 11 -1 3 9 -1 -1 //正則表達式查找 var str = "hello world 987 HELLO WORLD" var index = str.search(/[0-9]/) var index2 = str.search(/7/) var index3 = str.search(/[.]/) console.log(index) console.log(index2) console.log(index3) //輸出: 12 14 -1 //正則表達式匹配查找 var str = "hello 123 world 987 and 951" var result = str.match(/[0-9]+/g) console.log(result) //輸出: ["123", "987", "951"]
小結(jié)
-indexOf
是按照“從左往右
”的順序查找
-lastIndexOf
是按照“從右往左
”的順序查找
- 查找到則返回所在位置例书,沒有查找到則返回-1
-fromIndex
都是按照從左往右
計算的
小結(jié)
-
Java
和JS
的查找位置方法類似(indexOf
锣尉、lastIndexOf)
、查找到的位置决采,OC
查找到的是范圍range
十自沧、替換 replace
OC replace
-
方法
//把“源字符串”中所有的target字符替換為replacement - (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)); //把“源字符串”中searchRange范圍內(nèi)的target字符替換為replacement,通過options進行相關(guān)的控制树瞭,如忽略大小寫拇厢,傳0表示什么都不做 - (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement options:(NSStringCompareOptions)options range:(NSRange)searchRange API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)); //把“源字符串”中range范圍的字符,替換為replacement - (NSString *)stringByReplacingCharactersInRange:(NSRange)range withString:(NSString *)replacement API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)); //可變字符串-- - (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)aString; - (NSUInteger)replaceOccurrencesOfString:(NSString *)target withString:(NSString *)replacement options:(NSStringCompareOptions)options range:(NSRange)searchRange;
-
例子
//“源字符串”的所有范圍內(nèi)查找晒喷,替換 NSString *str = @"hello world"; NSString *result = [str stringByReplacingOccurrencesOfString:@"l" withString:@"0"]; NSLog(@"%@", result); //輸出: he00o wor0d NSString *str = @"hello world"; NSString *result = [str stringByReplacingOccurrencesOfString:@"ll" withString:@"0"]; NSLog(@"%@", result); //輸出: he0o world //“源字符串”的range范圍內(nèi)查找孝偎,替換 NSString *str = @"hello world"; NSString *result = [str stringByReplacingOccurrencesOfString:@"l" withString:@"0" options:0 range:NSMakeRange(0, 5)]; NSLog(@"%@", result); //輸出: he00o world //忽略大小寫的查找替換 L l NSString *str = @"hello world AND HELLO WORLD"; NSString *result = [str stringByReplacingOccurrencesOfString:@"L" withString:@"+" options:NSCaseInsensitiveSearch range:NSMakeRange(0, str.length)]; NSLog(@"%@", result); //輸出: he++o wor+d AND HE++O WOR+D //正則表達式查找字符串,并替換 NSString *str = @"hello world 12345679 hello"; NSString *result = [str stringByReplacingOccurrencesOfString:@"[0-9]+" withString:@"+" options:NSRegularExpressionSearch range:NSMakeRange(0, str.length)]; NSLog(@"%@", result); //輸出: hello world + hello //“源字符串”range范圍內(nèi)的字符替換為響應(yīng)的字符串 NSString *str = @"hello world"; NSString *result = [str stringByReplacingCharactersInRange:NSMakeRange(0, 5) withString:@"+"]; NSLog(@"%@", result);
小結(jié)
- 在“源字符”的全部
范圍進行查找凉敲、替換睦霎;- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
- 在“源字符”的range
范圍進行查找替換;- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement options:(NSStringCompareOptions)options range:(NSRange)searchRange API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
- 把“源字符”range
范圍的子字符串替換男窟;- (NSString *)stringByReplacingCharactersInRange:(NSRange)range withString:(NSString *)replacement API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
- “源字符串”全部/range范圍
進行全部/部分字符
替換
Java replace
-
方法
//用新字符newChar替換掉舊字符串oldChar public String replace(char oldChar, char newChar) //用心的字符串replacement替換掉目標字符串target public String replace(CharSequence target, CharSequence replacement) //用字符串replacement替換掉“所有”通過正則表達式regex查找的內(nèi)容 public String replaceAll(String regex, String replacement) //用字符串replacement替換掉“第一個”通過正則表達式regex查找的內(nèi)容 public String replaceFirst(String regex, String replacement)
-
例子
String str = "hello world 12345679 HELLO WORLD 987654"; String result = str.replace('l', '+'); Log.d("替換:", result); String result2 = str.replace("ll", "+"); Log.d("替換:", result2); String result3 = str.replaceAll("[0-9]+", "+"); Log.d("替換:", result3); String result4 = str.replaceFirst("[0-9]+", "+"); Log.d("替換:", result4); //輸出: he++o wor+d 12345679 HELLO WORLD 987654 he+o world 12345679 HELLO WORLD 987654 hello world + HELLO WORLD + hello world + HELLO WORLD 987654
小結(jié)
JS replace
-
方法
/** * “源字符”中把查找到的內(nèi)容(可以是“字符串常量substr”,也可以是“正則表達式regexp”) 用 newSubstr 進行替換 * ps: * 1迅涮、不會改變“源字符串”的值 * 2、替換的是“第一個”查找到的內(nèi)容 * 3徽龟、如果需要替換“所有”查找到的內(nèi)容,需要使用正則表達式唉地,加上 g 描述 (global的縮寫) * 4据悔、如果需要“忽略大小寫”的查找替換,需要使用正則表達式耘沼,加上 i 描述 */ str.replace(regexp|substr, newSubstr|function)
-
例子
//查找字符串常量并替換 var str = "hello world 01123 AND HELLO WORLD 321445" var result = str.replace("l", "+") console.log(str) console.log(result) //輸出: hello world 01123 AND HELLO WORLD 321445 he+lo world 01123 AND HELLO WORLD 321445 //正則表達式替換所有查找到的內(nèi)容 var str = "hello world 01123 AND HELLO WORLD 321445" var result = str.replace(/l/g, "+") console.log(str) console.log(result) //輸出: hello world 01123 AND HELLO WORLD 321445 he++o wor+d 01123 AND HELLO WORLD 321445 //忽略大小寫的极颓,使用真正表達式替換所有查找到的內(nèi)容 var str = "hello world 01123 AND HELLO WORLD 321445" var result = str.replace(/l/gi, "+") console.log(str) console.log(result) //輸出: hello world 01123 AND HELLO WORLD 321445 he++o wor+d 01123 AND HE++O WOR+D 321445
小結(jié)
- 替換字符串常量,使用引號""
("l"
)群嗤,使用正則表達式菠隆,/
開始,/
結(jié)束狂秘,不需要
加引號""
骇径,(/l/
)
- 查找替換全部使用g
標志
- 忽略大小寫使用i
標志
小結(jié)
-
replace
進行替換操作
十一、截取字符串 sub
OC substring
-
方法
//包含index位置的內(nèi)容 - (NSString *)substringFromIndex:(NSUInteger)from; //不包含index位置的內(nèi)容 - (NSString *)substringToIndex:(NSUInteger)to; - (NSString *)substringWithRange:(NSRange)range; // 字符序列判中字符范圍判斷 - (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)index; - (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
-
例子
NSString *str = @"0123456789"; NSString *substringFrom = [str substringFromIndex:5]; NSString *substringTo = [str substringToIndex:5]; NSString *substringRange = [str substringWithRange:NSMakeRange(1, 4)]; NSLog(@"From:%@", substringFrom); //From:56789 NSLog(@"To:%@", substringTo); //To:01234 NSLog(@"Range:%@", substringRange); //Range:1234 但是對于顯示的內(nèi)容需要多個`unicode`編碼組成的內(nèi)容(如`emoji`表情)者春,使用上面的方法會導致`emoji`表情從中間被截斷破衔,導致內(nèi)容顯示異常,所以需要使用下面的方法: //未處理前-------- NSString *str = @"0123\U0001F42E456789"; NSString *substringFrom = [str substringFromIndex:5]; NSString *substringTo = [str substringToIndex:5]; NSString *substringRange = [str substringWithRange:NSMakeRange(1, 4)]; NSLog(@"str:%@", str); //str:0123?456789 NSLog(@"length:%ld", str.length); //length:12 NSLog(@"From:%@", substringFrom); //From:\udc2e456789 NSLog(@"To:%@", substringTo); //To:0123 NSLog(@"Range:%@", substringRange); //Range:123 //處理后-------- NSString *str = @"0123\U0001F42E456789"; NSString *substringFrom = [str substringFromIndex:[str rangeOfComposedCharacterSequenceAtIndex:5].location]; NSString *substringTo = [str substringToIndex:NSMaxRange([str rangeOfComposedCharacterSequenceAtIndex:5])]; NSString *substringRange = [str substringWithRange:[str rangeOfComposedCharacterSequencesForRange:NSMakeRange(1, 4)]]; NSLog(@"str:%@", str); //str:0123?456789 NSLog(@"length:%ld", str.length); //length:12 NSLog(@"From:%@", substringFrom); //From:?456789 NSLog(@"To:%@", substringTo); //To:0123? NSLog(@"Range:%@", substringRange); //Range:123?
小結(jié)
- 可以看到钱烟,經(jīng)過處理之后的字符串截取晰筛,避免了字符串的截取位置導致的顯示異常,處理之后的字符串截取結(jié)果正常拴袭,也符合實際情況读第;
Java substring
-
方法
// “源字符串” 從 beginIndex 開始,一直截取到字符串末尾 public String substring(int beginIndex) // “源字符串” 從 beginIndex 開始拥刻,一直截取到 endIndex 位置 public String substring(int beginIndex, int endIndex) public CharSequence subSequence(int beginIndex, int endIndex)
-
例子
String str = "0123456789"; String substringFrom = str.substring(5); String substringTo = str.substring(0, 5); String substringRange = str.substring(1, 5); Log.e("substringFrom:", substringFrom); Log.e("substringTo:", substringTo); Log.e("substringRange:", substringRange); // 輸出: E/substringFrom:: 56789 E/substringTo:: 01234 E/substringRange:: 1234
-
小結(jié)
- 如果
beginIndex
或endIndex
為負
怜瞒,如果endIndex
大于length()
或beginIndex
大于startIndex
, 會拋出異常
- 如果
JS substring
泰佳、substr
盼砍、slice
-
方法
/** * 截取“源字符串”的 indexStart 位置到 indexEnd 位置的子字符串 * 1、包含 indexStart 位置字符逝她,不包含 indexEnd 位置字符 * 2浇坐、如果 indexStart 和 indexEnd 相等,返回空字符串 '' * 3黔宛、如果索引 index 小于 0 或者索引 index 為 NaN ,則當成 0 處理 * 4近刘、如果索引 index 大于 length,當成 length 處理 * 5、參數(shù) indexStart 和 indexEnd 觉渴,從這兩者中 較小 的索引位置處開始截取介劫,一直到 較大 的索引位置處,即使 indexStart 大于 indexEnd */ str.substring(indexStart[, indexEnd]) /** * 從“源字符串”的 start 位置處開始截取 length 長度的子字符串 * 1案淋、如果索引 start 小于 0 座韵,看成是 length + start , 如果 length + start 結(jié)果小于 0 踢京,當成 0 處理 * 2誉碴、如果索引 start 為 NaN ,則當成 0 處理 * 3、如果索引 start 大于 length 瓣距,返回空字符 '' * 4黔帕、length 是可選的,如果不傳入?yún)?shù)蹈丸,默認是 截取到字符串的結(jié)尾處 * 5成黄、如果 length 為 0 或者 負值,返回空字符串 '' */ str.substr(start[, length]) /** * 提取源字符串的 beginSlice(包含) 位置到 endSlice(不包含)位置的字符串 * 1逻杖、如果 beginSlice 或者 endSlice 為負數(shù)奋岁,則最終的索引值為 length + index * 2、endSlice 為負數(shù)荸百,可以看成是源字符串從后往前的索引(不包含) * 3厦取、如果 beginSlice 小于 endSlice ,返回空字符串 '' */ str.slice(beginSlice[, endSlice])
-
例子
//范圍截取 var str = "0123456789"; var substringFrom = str.substring(5); var substringTo = str.substring(0, 5); var substringRange = str.substring(1, 5); console.log("substringFrom:", substringFrom); console.log("substringTo:", substringTo); console.log("substringRange:", substringRange); //輸出: substringFrom: 56789 substringTo: 01234 substringRange: 1234 //截取的特殊情況 var str = "0123456789"; console.log(str.substring(1, 1)); console.log(str.substring(0, 5)); console.log(str.substring(-2, 5)); console.log(str.substring(NaN, 5)); console.log(str.substring(5, 15)); console.log(str.substring(5, -10)); console.log(str.substring(5, 2)); console.log(str.substring(2, 5)); console.log(str.substring(5, 9)); console.log(str.substring(5, 10)); console.log(str.substring(5, 11)); //輸出: 01234 01234 01234 56789 01234 234 234 5678 56789 56789 //長度截取 var str = "0123456789"; console.log(str.substr(5)); console.log(str.substr(0, 5)); console.log(str.substr(20)); console.log(str.substr(-20)); console.log(str.substr(NaN)); console.log(str.substr(-5, 2)); console.log(str.substr(-20, 2)); console.log(str.substr(5, -1)); console.log(str.substr(5, 0)); console.log("++++++++") //輸出: 56789 01234 0123456789 0123456789 56 01 ++++++++ var str = 'hello world'; var result = str.slice(1, 5); console.log(result); var result2 = str.slice(1, -1); console.log(result2); var result3 = str.slice(1, -2); console.log(result3); var result4 = str.slice(1, 0); console.log(result4); console.log("++++++++") //輸出: ello ello worl ello wor ++++++++
小結(jié)
1.substring
范圍截取
- 判斷indexStart
和indexEnd
管搪,如果小于 0
或者為NaN
,則當成0
處理虾攻,如果大于 length
,當成length
處理
- 從indexStart
和indexEnd
中較小
的位置處開始截取更鲁,一直到較大
的位置
- 如果indexStart
和indexEnd
相等霎箍,返回空字符串''
- 如果 只有一個參數(shù)indexStart
,則表示從indexStart
開始澡为,一直到字符串結(jié)尾漂坏,等價于indexStart
到length
- 如果indexStart
小于indexEnd
,substring(indexStart, indexEnd)
等價于substring(indexEnd, indexStart)
媒至,如上面的str.substring(5, 2)
和str.substring(2, 5)
1.substr
長度截取
- 判斷start
數(shù)值顶别,小于 0
,看成是length + start
拒啰, 如果length + start
結(jié)果小于 0
驯绎,當成0
處理
- 索引start
為NaN
,則當成0
處理
- 如果索引start
大于length - 1
,返回空字符''
-length
是可選的谋旦,如果不傳入?yún)?shù)剩失,默認是 截取到字符串的結(jié)尾
處
- 如果length
為0
或者負值
屈尼,返回空字符串''
小結(jié)
十二、大小寫 uppercase
拴孤、lowercase
OC uppercaseString
脾歧、lowercaseString
、capitalizedString
-
大寫
@property (readonly, copy) NSString *uppercaseString;
-
小寫
@property (readonly, copy) NSString *lowercaseString;
-
首字母大寫
@property (readonly, copy) NSString *capitalizedString;
-
例子:
NSString *str = @"Hello world"; NSLog(@"%@", str.uppercaseString); NSLog(@"%@", str.lowercaseString); NSLog(@"%@", str.capitalizedString); //打印: HELLO WORLD hello world Hello World
地區(qū)化
/* The following three return the locale-aware case mappings. They are suitable for strings presented to the user. */ @property (readonly, copy) NSString *localizedUppercaseString API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); @property (readonly, copy) NSString *localizedLowercaseString API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); @property (readonly, copy) NSString *localizedCapitalizedString API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); /* The following methods perform localized case mappings based on the locale specified. Passing nil indicates the canonical mapping. For the user preference locale setting, specify +[NSLocale currentLocale]. */ - (NSString *)uppercaseStringWithLocale:(nullable NSLocale *)locale API_AVAILABLE(macos(10.8), ios(6.0), watchos(2.0), tvos(9.0)); - (NSString *)lowercaseStringWithLocale:(nullable NSLocale *)locale API_AVAILABLE(macos(10.8), ios(6.0), watchos(2.0), tvos(9.0)); - (NSString *)capitalizedStringWithLocale:(nullable NSLocale *)locale API_AVAILABLE(macos(10.8), ios(6.0), watchos(2.0), tvos(9.0));
Java toUpperCase
演熟、 toLowerCase
-
大寫
public String toUpperCase() { }
-
小寫
public String toLowerCase() { }
-
例子:
String str = "Hello world"; Log.d("大小寫", str.toUpperCase()); Log.d("大小寫", str.toLowerCase()); //打印 HELLO WORLD hello world
地區(qū)化
public String toUpperCase(Locale locale) { } public String toLowerCase(Locale locale) { }
JS toUpperCase
鞭执、 toLowerCase
-
大寫
str.toUpperCase() //有返回值,返回值為"大寫"字母芒粹,不會影響原來字符串"str"的值
-
小寫
str.toLowerCase() //有返回值蚕冬,返回值為"小寫"字母,不會影響原來字符串"str"的值
-
例子:
var str = "hello world" console.log(str.toUpperCase()) console.log(str.toLowerCase()) //打印: HELLO WORLD hello world
地區(qū)化:
str.toLocaleLowerCase() str.toLocaleLowerCase(locale) str.toLocaleLowerCase([locale, locale, ...]) str.toLocaleUpperCase() str.toLocaleUpperCase(locale) str.toLocaleUpperCase([locale, locale, ...])
小結(jié)
- 大寫:
uppercase
- 小寫:
lowercase
十三是辕、過濾 trim
OC trim
-
方法
// 過濾字符串中的 首尾 在字符結(jié)合 set 中的字符 - (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set;
-
例子
NSString *str = @" \r \n \f \t \v hello \r \n \f \t \v "; NSString *result = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; NSLog(@"%@", result); // 輸出: hello
小結(jié)
Java trim
-
方法
public String trim()
-
例子
String str = " \r \n hello \r \n "; String result = str.trim(); Log.e("過濾", result); //輸出: E/過濾: hello
小結(jié)
JS trim
-
方法
//過濾首尾空白字符 str.trim()
-
例子
var str = " \r \n \f \t \v \ufeff hello \r \n \f \t \v \ufeff " var result = str.trim() console.log(result) //輸出: hello
小結(jié)
小結(jié)
十四、正則表達式 regex
猎提、match
相關(guān)知識
格式
/pattern/flags
-
pattern
中符號含義
-.
: 表示除了行結(jié)束符(\n
获三、\r
、\u2028
锨苏、\u2029
)以外的任意字符疙教;在字符集[]
中匹配的是一個字面量.
var str = "hello world 987 . HELLO WORLD" var result = str.search(/./) var result2 = str.search(/[.]/) console.log(result) console.log(result2) //輸出: 0 16 - `\d` : 表示匹配任意的阿拉伯數(shù)字,即 `0-9`伞租,`\d` 和 `[0-9]` 兩者等價 var str = "hello world 987 . HELLO WORLD" var result = str.search(/\d/) var result2 = str.search(/[0-9]/) console.log(result) console.log(result2) //輸出: 12 12 - `\D` : 表示匹配任意的`非`阿拉伯數(shù)字贞谓,`\D` 和 `[^0-9]` 兩者等價 var str = "hello world 987 . HELLO WORLD" var result = str.search(/\D/) var result2 = str.search(/[^0-9]/) console.log(result) console.log(result2) //輸出: 0 0 - `\w` : 表示匹配任意的`大寫字母`、`小寫字母`葵诈、`阿拉伯數(shù)字`裸弦、`下劃線`,`\w` 和 `[A-Za-z0-9_]` 兩者等價 var str = "% hello WORLD _ . " var result = str.search(/\w/) var result2 = str.search(/[A-Za-z0-9_]/) console.log(result) console.log(result2) //輸出: 2 2 - `\W` : 表示匹配任意的`“非”` `大寫字母`作喘、`小寫字母`理疙、`阿拉伯數(shù)字`、`下劃線`泞坦,`\W` 和 `[^A-Za-z0-9_]` 兩者等價 var str = "hello % WORLD _ . " var result = str.search(/\W/) var result2 = str.search(/[^A-Za-z0-9_]/) console.log(result) console.log(result2) //輸出: 5 5 - `\s` : 表示匹配任意的`空白符`窖贤,包含`空格`、`制表符`(`\t` 和 `\v`)贰锁、`換頁符`(`\f`)赃梧、`換行符`(`\r` 和 `\n`)和`其他 Unicode 空格`,`\s` 和 `[ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff] ` 兩者等價 var str = "hello % WORLD _ . " var result = str.search(/\s/) var result2 = str.search(/`[ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]`/) console.log(result) console.log(result2) //輸出: 5 5 - `\S` : 表示匹配任意的 `非` `空白符`豌熄,`\S` 和 `[^ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]` 兩者等價 var str = "hello % WORLD _ . " var result = str.search(/\S/) var result2 = str.search(/[^ `[^ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]`/) console.log(result) console.log(result2) //輸出: 0 0 - `\t` : 匹配一個水平制表符(tab) - `\v` : 匹配一個垂直制表符(vertical tab) - `\r` : 匹配一個回車符(carriage return) - `\n` : 匹配一個換行符(linefeed) - `\f` : 匹配一個換頁符(form-feed) - `[\b]` : 匹配一個退格符(backspace)(不要與 `\b` 混淆) - `\0` : 匹配一個 `NUL` 字符授嘀。不要在此后面跟小數(shù)點 - `\cX` : `X` 是 `A - Z` 的一個字母。匹配字符串中的一個`控制`字符 - `\xhh` : 匹配編碼為 `hh` (兩個十六進制數(shù)字)的字符 - `\uhhhh` : 匹配 `Unicode` 值為 `hhhh` (四個十六進制數(shù)字)的字符 var str = "hello ? 013a" var result = str.search(/\u0240/) var result2 = str.search(/\u0068/) //u0068 對應(yīng)的字符 為 h console.log(result) console.log(result2) //輸出: 6 0 - `\` : 把特殊字符當做字面意義解釋锣险;`*` 是一個特殊字符粤攒,表示匹配某個字符 0 或多次所森,如 `/a*/` 意味著 0 或多個 "`a`"。 為了匹配字面意義上的 `*`夯接,在它前面加上一個反斜杠焕济,例如,`/a\*/`匹配 `'a*'` - `[]` : 字符集合盔几,表示匹配`集合中`的任意一個字符晴弃,可以使用連字符`-`指定一個范圍,如 `[abcd]` 等價于 `[a-d]` - `[^]` : 反義字符集合逊拍,表示匹配字符`集合以外`的字符上鞠,可以使用連字符`-`指定一個范圍,`[^abc]` 等價于 `[^a-c]` - `^` : 匹配輸入的開始芯丧,`/^A/` 不匹配 "`an A`" 中的 "`A`"芍阎,但匹配 "`An A`" 中的 "`A`";`^` 在`字符集合`中表示`相反`的意思缨恒,但是在正則表達式直接量中表示字符開始谴咸;有點類似`前綴` var str = "hello ? 013a" var result = str.search(/^h/) var result2 = str.search(/^l/) console.log(result) console.log(result2) //輸出: 0 -1 - `$` : 匹配輸入結(jié)尾,`/t$/` 不匹配 "`eater`" 中的 "`t`"骗露,但匹配 "`eat`" 中的 "`t`"岭佳,有點類似`后綴` var str = "eater" var result = str.search(/t$/) var result2 = str.search(/r$/) console.log(result) console.log(result2) //輸出: -1 4 - `\b` : 匹配一個零寬`單詞邊界`,`/\b.../`萧锉,以`...`開始的單詞珊随,`/...\b/`,以`...`結(jié)尾的單詞柿隙;`/\bno/` 匹配 "at noon" 中的 "no"叶洞,`/ly\b/` 匹配 "possibly yesterday." 中的 "ly"; var str = "at noon" var result = str.search(/\bno/) console.log(result) //輸出: 3 - `\B` : 匹配一個零寬非單詞邊禀崖,`/\Bon/` 匹配 "at noon" 中的 "on"京办,`/ye\B/` 匹配 "possibly yesterday." 中的 "ye" - `(x)` : 匹配 `x` 并且`捕獲匹配項結(jié)果`。 這被稱為捕獲括號`(capturing parentheses)`帆焕。被匹配的子字符串`可以`在結(jié)果數(shù)組的元素 `[1], ..., [n]` 中找到惭婿,或在被定義的 `RegExp` 對象的屬性 `$1, ..., $9` 中找到。會消耗性能叶雹。 var str = "hello 123 world 987 and 951" var result = str.match(/([0-9]+)/g) console.log(result) //輸出: ["123", "987", "951"] - `(?:x)` : 匹配 `x` `不會`捕獲匹配項财饥。這被稱為非捕獲括號`(non-capturing parentheses)`。匹配項`不能`夠從結(jié)果數(shù)組的元素 `[1], ..., [n]` 或已被定義的 `RegExp` 對象的屬性 `$1, ..., $9` 再次訪問到折晦。 var str = "hello 123 world 987 and 951" var result = str.match(/(?:[0-9]+)/g) console.log(result) //輸出: ["123", "987", "951"] - `x*` : 匹配前面的模式 x `0 或多次`钥星。例如,`/bo*/` 匹配 "`A ghost booooed`" 中的 "`boooo`"满着,"`A bird warbled`" 中的 "`b`"谦炒,但是不匹配 "`A goat grunted`"贯莺。 - `x+` : 匹配前面的模式 x `1 或多次`。等價于 `{1,}`宁改。例如缕探,`/a+/` 匹配 "`candy`" 中的 "`a`","`caaaaaaandy`" 中`所有`的 "`a`"还蹲。 - `x?` : 匹配前面的模式 x `0 或 1 次`爹耗。 - `x(?=y)` : 只有當 `x` 后面緊跟著 `y` 時,才匹配 `x`谜喊。 例如潭兽,`/Jack(?=Sprat)/` 只有在 '`Jack`' 后面緊跟著 '`Sprat`' 時,才會匹配它斗遏。`/Jack(?=Sprat|Frost)/` 只有在 '`Jack`' 后面緊跟著 '`Sprat`' 或 '`Frost`' 時山卦,才會匹配它。然而诵次,'`Sprat`' 或 '`Frost`' 都`不是`匹配結(jié)果的一部分账蓉。 - `x(?!y)` : 只有當 `x` 后面`不是`緊跟著 `y` 時,才匹配 `x`藻懒。例如,`/\d+(?!\.)/` 只有當一個數(shù)字后面沒有緊跟著一個小數(shù)點時视译,才會匹配該數(shù)字嬉荆。`/\d+(?!\.)/.exec("3.141")` 匹配 `141` 而不是 `3.141`。 - `x|y` : 匹配 `x` 或 `y` **酷含,例如鄙早,`/green|red/` 匹配 "`green apple`" 中的 ‘`green`',"`red apple`." 中的 '`red`'椅亚。 - `x{n}` : `n` 是一個正整數(shù)限番。前面的模式 x `連續(xù)出現(xiàn) n 次時匹配`。 - `x{n,}` : `n` 是一個正整數(shù)呀舔。前面的模式 x `連續(xù)出現(xiàn)至少 n 次時匹配`弥虐。 - `x{n,m}` : `n` 和 `m` 為正整數(shù)。前面的模式 x `連續(xù)出現(xiàn)至少 n 次媚赖,至多 m 次時匹配`霜瘪。
-
flags
中符號含義-
g
: 全局匹配;找到所有匹配,而不是在第一個匹配后停止 -
i
: 忽略大小寫 -
m
: 多行; 將開始和結(jié)束字符(^
和$
)視為在多
行上工作(也就是惧磺,分別匹配每一行的開始和結(jié)束(由\n
或\r
分割)颖对,而不只是只匹配整個輸入字符串的最開始和最末尾處。 -
u
:Unicode
; 將模式視為Unicode
序列點的序列 -
y
: 粘性匹配; 僅匹配目標字符串中此正則表達式的lastIndex
屬性指示的索引(并且不嘗試從任何后續(xù)的索引匹配)磨隘。
-
-
OC
詳情見 `NSRegularExpression` 類
Java matches
-
方法
public boolean matches(String regex) Pattern.matches( regex , str )
-
例子
String str = "hello 123 world 987 and 951"; boolean result = str.matches("[0-9]+"); Log.e("正則表達式", String.valueOf(result)); // 輸出: E/正則表達式: false String str = "123456"; boolean result = str.matches("[0-9]+"); Log.e("正則表達式", String.valueOf(result)); // 輸出: E/正則表達式: true
小結(jié)
-matches
是全局匹配缤底,即整個字符串都是匹配的才返回true
顾患,否則返回false
JS match
-
方法
/* * 沒有匹配到返回 null * 匹配到返回匹配的結(jié)果數(shù)組 */ str.match(regexp) /** * 根據(jù)正則表達式查找內(nèi)容 * 1、查找到則返回所在位置个唧,沒有查找到則返回 -1 */ str.search(regexp)
-
例子
var str = "hello 123 world 987 and 951" var result = str.match(/[0-9]+/g) console.log(result) //輸出: ["123", "987", "951"]
小結(jié)
小結(jié)
十五江解、字符串和其他類型的轉(zhuǎn)化 parse
、valueOf
OC
-
字符串轉(zhuǎn)數(shù)字等
@property (readonly) double doubleValue; @property (readonly) float floatValue; @property (readonly) int intValue; @property (readonly) NSInteger integerValue API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)); @property (readonly) long long longLongValue API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)); @property (readonly) BOOL boolValue API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
-
數(shù)字等轉(zhuǎn)字符串
- (instancetype)initWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2); - (instancetype)initWithFormat:(NSString *)format arguments:(va_list)argList NS_FORMAT_FUNCTION(1,0); + (instancetype)stringWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2); - (instancetype)initWithFormat:(NSString *)format locale:(nullable id)locale, ... NS_FORMAT_FUNCTION(1,3); - (instancetype)initWithFormat:(NSString *)format locale:(nullable id)locale arguments:(va_list)argList NS_FORMAT_FUNCTION(1,0); + (instancetype)localizedStringWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
Java valueOf
-
字符串轉(zhuǎn)數(shù)字等
public static Integer valueOf(String s) .... 依次類推
-
數(shù)字等轉(zhuǎn)字符串
public static String valueOf(boolean b) public static String valueOf(char c) public static String valueOf(int i) public static String valueOf(long l) public static String valueOf(float f) public static String valueOf(double d)
JS parseInt
坑鱼、parseFloat
膘流、toString
、 +
-
字符串轉(zhuǎn)數(shù)字
- 方法/** * 把字符串 string 轉(zhuǎn)化為 radix 進制的整數(shù)數(shù)值鲁沥,返回值為 整數(shù)number 或 NaN * 1呼股、要明確給出radix參數(shù)的值 * 2、在沒有指定基數(shù)画恰,或者基數(shù)為 0 的情況下彭谁,JavaScript 作如下處理: * - 如果字符串 string 以"0x"或者"0X"開頭, 則基數(shù)是16 (16進制). * - 如果字符串 string 以"0"開頭, 基數(shù)是8(八進制)或者10(十進制),那么具體是哪個基數(shù)由實現(xiàn)環(huán)境決定允扇。ECMAScript 5 規(guī)定使用10缠局,但是并不是所有的瀏覽器都遵循這個規(guī)定。因此考润,永遠都要明確給出radix參數(shù)的值狭园。 * - 如果字符串 string 以其它任何值開頭,則基數(shù)是10 (十進制)糊治。 */ parseInt(string, radix); /** * 把字符串 string 轉(zhuǎn)化為 radix 進制的小數(shù)數(shù)值唱矛,返回值為 小數(shù)number 或 NaN */ parseFloat(string) - 例子 console.log(parseInt('0Xa0')) console.log(parseInt('010')) console.log(parseInt('08')) console.log(parseInt('20')) //輸出: 160 10 8 20 - 小結(jié) - 參數(shù) `radix` 需要指定,防止一些不必要的錯誤 - 當無法轉(zhuǎn)化為數(shù)字時井辜,返回`NaN`
-
數(shù)字轉(zhuǎn)字符串
- 方法/** * 把數(shù)字轉(zhuǎn)化為 radix進制的字符串形式 * 1绎谦、radix :可選值,不傳默認為10進制 * 2粥脚、radix :取值 2-36 之間的整數(shù)窃肠,其他會拋出異常RangeError */ numObj.toString([radix]) //使用加號+拼接 '' + number - 例子 var num = 123; console.log(num.toString()); console.log('' + 123); //輸出: 123 123 - 小結(jié)
十六、分割字符串為數(shù)組 Separated
刷允、split
OC Separated
-
方法
// 根據(jù) 指定的字符串 separator 進行分割 - (NSArray<NSString *> *)componentsSeparatedByString:(NSString *)separator; // 根據(jù) 指定的字符集合 separator 進行分割 - (NSArray<NSString *> *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
-
例子
NSString *str = @"hello 123 world 456 nice 987"; NSArray *array = [str componentsSeparatedByString:@" "]; NSLog(@"%@", array); NSArray *array2 = [str componentsSeparatedByCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]]; NSLog(@"%@", array2); // 輸出: ( hello, 123, world, 456, nice, 987 ) ( "hello ", "", "", " world ", "", "", " nice ", "", "", "" )
小結(jié)
-componentsSeparatedByString
是根據(jù)給定的字符串進行分割
-componentsSeparatedByCharactersInSet
是根據(jù)給定的字符集合分割冤留,查找到一個符合的字符就當成是一個分隔符進行分割,如上面的例子中123
树灶,1
進行分割一次得到hello
搀菩,2
進行分割一次得到""
瞻讽,3
進行分割一次得到""
Java split
-
方法
// 根據(jù)正則表達式 regex 分割字符串 public String[] split(String regex) // 根據(jù)正則表達式 regex 分割字符串颓屑,最終是分割成 limit 部分 public String[] split(String regex, int limit)
-
例子
String str = "hello 123 world 456 nice 987"; String[] result = str.split(" "); Log.e("分割", String.valueOf(result.length)); for (int i = 0; i < result.length; i++) { Log.e("分割", result[i]); } // 輸出: E/分割: 6 E/分割: hello E/分割: 123 E/分割: world E/分割: 456 E/分割: nice E/分割: 987 String str = "hello 123 world 456 nice 987"; String[] result = str.split("[\\d]+"); Log.e("分割", String.valueOf(result.length)); for (int i = 0; i < result.length; i++) { Log.e("分割", result[i]); } // 輸出: E/分割: 3 E/分割: hello E/分割: world E/分割: nice String str = "hello 123 world 456 nice 987"; String[] result = str.split("[\\d]+", 2); Log.e("分割", String.valueOf(result.length)); for (int i = 0; i < result.length; i++) { Log.e("分割", result[i]); } // 輸出: E/分割: hello E/分割: world 456 nice 987
小結(jié)
- 會過濾最后的空字符""
JS split
-
方法
/** * 把字符串根據(jù)指定的分隔符 separator 進行分割字符串鸠天,返回字符串數(shù)組前 limit 個元素組成的子數(shù)組 * 1检柬、separator 可以是 字符串常量 或者 正則表達式 * 2宝冕、對于正則表達式咸作,如果需要返回匹配到的內(nèi)容浙值,需要加掛號 () * 3羔巢、如果 字符串的第一個或者最后一個 和 分隔符匹配,也會進行分割吴叶,元素是空字符串 "" */ str.split([separator[, limit]])
-
例子
var str = 'hello 123 world 456 nice 987'; var result = str.split(' '); console.log(result); //輸出: ["hello", "123", "world", "456", "nice", "987"] var result2 = str.split(' ', 2); console.log(result2); //輸出: ["hello", "123"] var result3 = str.split(/\d+/); console.log(result3); //輸出: ["hello ", " world ", " nice ", ""] //因為最后一個是數(shù)字阐虚,所以分割后的字符串數(shù)組,最后一個元素為空字符串 var result4 = str.split(/(\d+)/); console.log(result4); //輸出: ["hello ", "123", " world ", "456", " nice ", "987", ""]
小結(jié)
- 根據(jù)字符串常量
或正則表達式
進行分割
- 如果字符串的第一個
或者最后一個
和 分隔符匹配蚌卤,也會進行分割实束,元素是空字符串""
小結(jié)
-
js
和oc
分割不會過濾最后的空字符""
,java
分割會過濾最后的空字符""
十七逊彭、編碼
OC
概念
- OC中的字符串
NSSring
是由有序
的UTF-16
編碼的"單元
"(code units
咸灿,characters
)組成的 - 長度
length
、索引index
侮叮,范圍range
都是基于字符串的UTF-16
的編碼"單元"處理和操作的 - "單元"
code units
用unichar
類型表示(無符號的short
類型避矢,typedef unsigned short unichar
),2
字節(jié)囊榜,16
位审胸,范圍為0~32767
編碼方式
typedef NSUInteger NSStringEncoding;
NS_ENUM(NSStringEncoding) {
NSASCIIStringEncoding = 1, /* 0..127 only */
NSNEXTSTEPStringEncoding = 2,
NSJapaneseEUCStringEncoding = 3,
NSUTF8StringEncoding = 4,
NSISOLatin1StringEncoding = 5,
NSSymbolStringEncoding = 6,
NSNonLossyASCIIStringEncoding = 7,
NSShiftJISStringEncoding = 8, /* kCFStringEncodingDOSJapanese */
NSISOLatin2StringEncoding = 9,
NSUnicodeStringEncoding = 10,
NSWindowsCP1251StringEncoding = 11, /* Cyrillic; same as AdobeStandardCyrillic */
NSWindowsCP1252StringEncoding = 12, /* WinLatin1 */
NSWindowsCP1253StringEncoding = 13, /* Greek */
NSWindowsCP1254StringEncoding = 14, /* Turkish */
NSWindowsCP1250StringEncoding = 15, /* WinLatin2 */
NSISO2022JPStringEncoding = 21, /* ISO 2022 Japanese encoding for e-mail */
NSMacOSRomanStringEncoding = 30,
NSUTF16StringEncoding = NSUnicodeStringEncoding, /* An alias for NSUnicodeStringEncoding */
NSUTF16BigEndianStringEncoding = 0x90000100, /* NSUTF16StringEncoding encoding with explicit endianness specified */
NSUTF16LittleEndianStringEncoding = 0x94000100, /* NSUTF16StringEncoding encoding with explicit endianness specified */
NSUTF32StringEncoding = 0x8c000100,
NSUTF32BigEndianStringEncoding = 0x98000100, /* NSUTF32StringEncoding encoding with explicit endianness specified */
NSUTF32LittleEndianStringEncoding = 0x9c000100 /* NSUTF32StringEncoding encoding with explicit endianness specified */
};
//常用的:
NSASCIIStringEncoding : ACII編碼,只有0-127個字符
NSUTF8StringEncoding : UTF-8編碼卸勺,常用的砂沛,1個字節(jié)表示code point
NSUnicodeStringEncoding : Unicode編碼,國際統(tǒng)一的曙求,2個字節(jié)表示一個code point
其他
@property (readonly) NSStringEncoding fastestEncoding; // Result in O(1) time; a rough estimate
@property (readonly) NSStringEncoding smallestEncoding; // Result in O(n) time; the encoding in which the string is most compact
@property (class, readonly) const NSStringEncoding *availableStringEncodings;
@property (class, readonly) NSStringEncoding defaultCStringEncoding; // Should be rarely used
+ (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding;
字節(jié)大小
-
方法
//是否可以轉(zhuǎn)化為相應(yīng)的編碼方式 - (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding; //“預估”轉(zhuǎn)化為enc編碼方式的所占的字節(jié)大小 - (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc; // Result in O(1) time; the estimate may be way over what's needed. Returns 0 on error (overflow) //“準確”計算轉(zhuǎn)化為enc編碼方式所占的字節(jié)大小 - (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc; // Result in O(n) time; the result is exact. Returns 0 on error (cannot convert to specified encoding, or overflow)
-
例子
NSString *str = @"hello world"; if ([str canBeConvertedToEncoding:NSUTF8StringEncoding]) { NSUInteger maximumLength = [str maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding]; NSUInteger length = [str lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; NSLog(@"%ld", maximumLength); NSLog(@"%ld", length); } else { } //編碼方式為 NSUTF8StringEncoding : 33 11 //編碼方式為 NSUTF16StringEncoding : 22 22 UTF-8編碼碍庵,一個單元`code points`用`8`位(1個字節(jié)byte)表示;UTF-16編碼方式圆到,一個單元`code points`用`16`位(2個字節(jié)byte)表示怎抛,所以才有了?的輸出結(jié)果卑吭,UTF-16編碼方式的字節(jié)數(shù)長度是UTF-8的`兩倍`
字符串和二進制數(shù)據(jù)的轉(zhuǎn)化
-
方法
[//NSSring](//nssring) 轉(zhuǎn) NSData - (nullable NSData *)dataUsingEncoding:(NSStringEncoding)encoding allowLossyConversion:(BOOL)lossy; - (nullable NSData *)dataUsingEncoding:(NSStringEncoding)encoding; //NSData 轉(zhuǎn) NSSring - (nullable instancetype)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding;
-
例子
NSString *str = @"hello world"; NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding]; NSLog(@"%@", data); NSString *resultStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", resultStr); //打印: <68656c6c 6f20776f 726c64> hello world
字符串和c語言字符串的轉(zhuǎn)化
-
方法
//oc字符串轉(zhuǎn)c字符串-------- //轉(zhuǎn)化為encoding編碼方式的c語言字符串芽淡,支持8位編碼,不支持UTF-16,UTF-32等非8位編碼方式 - (nullable const char *)cStringUsingEncoding:(NSStringEncoding)encoding NS_RETURNS_INNER_POINTER; - (BOOL)getCString:(char *)buffer maxLength:(NSUInteger)maxBufferCount encoding:(NSStringEncoding)encoding; //快速的獲取UTF-8編碼方式的c語言字符串 @property (nullable, readonly) const char *UTF8String NS_RETURNS_INNER_POINTER; //c字符串轉(zhuǎn)oc字符串-------- //c字符串cString通過enc編碼方式轉(zhuǎn)為oc字符串 - (nullable instancetype)initWithCString:(const char *)nullTerminatedCString encoding:(NSStringEncoding)encoding; + (nullable instancetype)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc; //c字符串nullTerminatedCString轉(zhuǎn)化為UTF-8編碼方式的oc字符串 - (nullable instancetype)initWithUTF8String:(const char *)nullTerminatedCString; + (nullable instancetype)stringWithUTF8String:(const char *)nullTerminatedCString;
-
例子
//oc字符串轉(zhuǎn)c字符串-------- NSString *str = @"hello world"; const char *UTF8Str = str.UTF8String; const char *ASCIIStr = [str cStringUsingEncoding:NSASCIIStringEncoding]; const char *UTF16Str = [str cStringUsingEncoding:NSUTF16StringEncoding]; NSLog(@"%s", UTF8Str); NSLog(@"%s", ASCIIStr); NSLog(@"%s", UTF16Str); //打印: hello world hello world h //c字符串轉(zhuǎn)oc字符串-------- const char *cStr = "hello world"; NSString *ocStr = [[NSString alloc] initWithCString:cStr encoding:NSUTF16StringEncoding]; NSLog(@"%@", ocStr); const char *UTF8Str = "hello world"; NSString *str = [[NSString alloc] initWithUTF8String:UTF8Str]; NSLog(@"%@", str); //打印: hello world hello world 可以看到豆赏,使用`cStringUsingEncoding`方法進行編碼時挣菲,如果傳入的不是8位編碼,會導致結(jié)果錯誤;
字符串和字節(jié)的轉(zhuǎn)化
十八掷邦、保存到文件
OC
-
方法
- (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)useAuxiliaryFile encoding:(NSStringEncoding)enc error:(NSError **)error; - (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile encoding:(NSStringEncoding)enc error:(NSError **)error;
例子
小結(jié)
最后吐槽一下: 這些原先是在notion
上進行文章編輯的白胀,后面導出為markdown的時候,有些格式混亂了抚岗,so 就變成了上面的樣子了或杠。。宣蔚。