編程語言對比系列:一、字符串的基本使用

前言

最先接觸編程的知識是在大學裏面,大學裏面學了一些基礎的知識,c語言,java語言,單片機的彙編語言等;大學畢業後就開始了app的開發之路,先使用oc進行iOSapp開發,後面應公司需求,又相繼學習了java語言並使用java語言進行Androidapp開發,後來微信開放了小程序,應公司需求,又學習了小程序的相關知識,jscsshtml等,腦袋裏面有了這麼多的編程語言,有時候會有點混亂,因此想到了把這些編程語言的一些內容進行對比、梳理,可以找到他們的相同點和不同點,結果是很好的,讓自己的知識更加有深度了,也更加全面了。這篇文章是第一篇,選擇的是字符串string,後續會繼續更新其他內容的對比。

正在前往全棧的路上!!!

編程語言對比系列:一、字符串的基本使用

大綱爲

image

名詞解釋

  • code point : 用來表示unicode編碼表中的字符character的一個十六進制的數字(日常使用中十六進制、進制數字都是可以的),a hexadecimal number that is used to represent that character in computer data, 如 :

    code point 0x4E00 對應的 character ;

    code point 0x41 對應的 characterA ;

  • code unit : 表示一個unicode編碼表中的字符character所需要的二進制位數bitsA 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字符所需要的二進制位數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)
-----------


-----------
  • 圖片

    • 字符串未初始化
      字符串未初始化

    • 初始化一個空的字符串
      初始化一個空的字符串

  • 小結

    • 字符串未初始化話的時候,指針爲nil,值爲(null)
    • 初始化空字符串之後,指針不爲空,值爲@""

二進制 NSData (準確的說應該是十六進制

  • 方法
- (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>
潮
  • 小結

    • 同樣的二進制數據,因爲編碼方式的不同,獲取到的結果也不同,優先使用NSUTF8StringEncoding
    • 編碼方式對應的所需字節數如下:
      編碼方式對應字節數

      • UTF-8編碼方式處理二進制數6f6e656f6e65,看成是三個單元處理,在ASCII碼錶中對應的值依次爲one,所以輸出one
      • Unicode編碼方式處理二進制數6f6e656f6e 65,看成是兩個單元處理,一個是完整的6f6e(保留),一個不是完整的65(捨棄),在Unicode編碼表中對應的值爲漢字,所以輸出
      • 所以得到的結果如上,?

通過字節bytes

  • 方法
//bytes : 字節數,從緩存buffer中讀取,是指向buffer地址的指針,指向的是在緩存中的地址
//len : 需要讀取bytes的長度,如bytes爲3,len參數爲1,則只會讀取bytes中的前1個byte
//encoding : 編碼方式
//freeBuffer : 操作之後是否釋放掉內存
- (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參數傳10x600000017600
o
  • 小結
    • 從緩存buffer中讀取length長度的字節bytes構建字符串

字符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);
// 輸出:
+++
  • 小結
    • 通過 unicode 字符構建字符串,可以使用 十六進制十進制字符

通過OC字符串 NSString

  • 方法
//通過其他"oc字符串"初始化
- (instancetype)initWithString:(NSString *)aString;
+ (instancetype)stringWithString:(NSString *)string;

//通過其他"oc字符串"初始化,帶有參數的,可以作爲字符串拼接使用
- (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
  • 小結

    • 如果是通過字符串常量進行初始化,不推薦使用上面方法,使用下面的寫法

        NSString *str = @"one";
      

c字符串CString

  • 方法
//把c字符串用encoding編碼方式轉化爲OC字符串
- (nullable instancetype)initWithCString:(const char *)nullTerminatedCString encoding:(NSStringEncoding)encoding;
+ (nullable instancetype)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc;

//把c字符串用UTF-8編碼方式轉化爲OC字符串
- (nullable instancetype)initWithUTF8String:(const char *)nullTerminatedCString;
+ (nullable instancetype)stringWithUTF8String:(const char *)nullTerminatedCString;
  • 例子
//按照指定編碼方式把c字符串轉化爲oc字符串
const char *cStr = "c string";
NSString *str = [NSString stringWithCString:cStr encoding:NSUTF8StringEncoding];
NSLog(@"%@", str);

//輸出
c string

//如果使用的是NSUnicodeStringEncoding編碼方式,輸出爲:
撓獴物湧



//按照UTF-8編碼方式把c字符串轉化爲oc字符串
const char *cStr = "c string";
NSString *str = [NSString stringWithUTF8String:cStr];
NSLog(@"%@", str);

//輸出:
c string
  • 小結
    • 相同的c字符串,使用不同的編碼方式得到的結果不一樣,優先使用NSUTF8StringEncoding編碼方式

通過URLNSURL

  • 方法

        //使用指定的編碼方式
        - (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="//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="//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" href='https://developer.apple.com/'>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&#133;</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="//apple_ref/doc/uid/10000051i-CH6-SW1" title="String Resources"></a><h1 id="pageTitle">String Resources</h1><p><a name="//apple_ref/doc/uid/10000051i-CH6-DontLinkElementID_5"></a><a name="//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="//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>&nbsp;&nbsp;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="//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="//apple_ref/doc/uid/10000051i-CH6-SW4" title="Note"></a><p><strong>Note:</strong>&nbsp;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 href="http://www.unicode.org/" class="urlLink" rel="external">http://www.unicode.org/</a></span> or <span class="content_text"><a href="http://en.wikipedia.org/wiki/Unicode" 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="//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="//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", &amp;first, &amp;last, &amp;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="//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 href="https://developer.apple.com/documentation/corefoundation/cfcopylocalizedstring" target="_self" class="urlLink">CFCopyLocalizedString</a></code></p></li><li class="nested li"><p><code><a href="https://developer.apple.com/documentation/corefoundation/cfcopylocalizedstringfromtable" target="_self" class="urlLink">CFCopyLocalizedStringFromTable</a></code></p></li><li class="nested li"><p><code><a href="https://developer.apple.com/documentation/corefoundation/cfcopylocalizedstringfromtableinbundle" target="_self" class="urlLink">CFCopyLocalizedStringFromTableInBundle</a></code></p></li><li class="nested li"><p><code><a href="https://developer.apple.com/documentation/corefoundation/cfcopylocalizedstringwithdefaultvalue" 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 href="https://developer.apple.com/documentation/foundation/nslocalizedstring" target="_self" class="urlLink">NSLocalizedString</a></code></p></li><li class="nested li"><p><code><a href="https://developer.apple.com/documentation/foundation/nslocalizedstringfromtable" target="_self" class="urlLink">NSLocalizedStringFromTable</a></code></p></li><li class="nested li"><p><code><a href="https://developer.apple.com/documentation/foundation/nslocalizedstringfromtableinbundle" target="_self" class="urlLink">NSLocalizedStringFromTableInBundle</a></code></p></li><li class="nested li"><p><code><a href="https://developer.apple.com/documentation/foundation/nslocalizedstringwithdefaultvalue" 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="//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="//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="//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="//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>&nbsp;&nbsp;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="//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>&nbsp;&nbsp;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="//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="//apple_ref/doc/uid/20000005-97055" title="Loading String Resources Into Your Code"></a><a name="//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="//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>&nbsp;&nbsp;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 href="http://en.wikipedia.org/wiki/Extended_ASCII" 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 href="https://developer.apple.com/documentation/foundation/nsbundle" 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 href="https://developer.apple.com/documentation/foundation/nsbundle" target="_self" class="urlLink">NSBundle</a></code> object or <code><a href="https://developer.apple.com/documentation/corefoundation/cfbundle" 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="//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=
    
  • 小結

    • 通過讀取url的內容,並使用響應的編碼方式(一般爲UTF-8)轉化爲字符串
    • 如果url內容加載失敗,或者編碼方式錯誤,初始化失敗,返回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) 文件內容爲 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!
    
  • 小結

    • 讀取本地文件file內容,並按照響應的編碼方式(一般爲UTF-8)轉化爲字符串
    • 如果file內容加載失敗,或者編碼方式錯誤,初始化失敗,返回nil

Java new String

初始化一個的字符串 ""

      String str = "";

通過字符串String

  • 方法

        public String(String original) { }
    
  • 例子

        String str = new String("hello");
        Log.d("字符串", str);
    
        //輸出:
        hello
    
  • 小結

    • 如果是通過一個字符串常量初始化,則不推薦使用上面方法,直接複製即可,如下

        String str = "hello";
      

通過字符char UTF-16 code units

  • 方法

        //字符數組
        public String(char[] value) { }
    
        /**
         *  value - 作爲字符源的數組。 
            offset - 初始偏移量。 
            count - 長度。
         */
        //從字符源數組value的offset索引位置處連續取出count長度的的子數組構建字符串
        //如果 offset 和 count 參數索引字符超出 value 數組的範圍,則會拋出異常 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無
    
        //從字符源數組value的offset索引位置處連續取出count長度的的子數組構建字符串
        char [] chars = new char[3];
        chars[0] = 'h';
        chars[1] = 'e';
        chars[2] = '無';
        String str = new String(chars, 1, 2);
        Log.d("字符串", str);
    
        //輸出:
        e無
    
  • 小結

    • java字符串用雙引號""(String),字符用單引號''(char)
    • 字符串String是由字符char作爲單元構成的,char作爲java中字符串的基本單元code unit

通過unicode points代碼點

  • 方法

        /*
         * codePoints - 作爲 Unicode 代碼點的源的數組。
             offset - 初始偏移量。
             count - 長度。
         */
        //從Unicode代碼點的源的數組codePoints的offset索引位置處連續取出count長度的的子數組構建字符串
        //如果 offset 和 count 參數索引字符超出 value 數組的範圍,則會拋出異常 IndexOutOfBoundsException
        //如果在 codePoints 中發現任何無效的 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
    
  • 小結

    • codePoints是字符串單元對應的十進制數字,104對應h101對應e
    • code point先轉換爲字符charchar再轉化爲字符串String,即code point —> char —> String

通過字符集 bytes Charset

  • 方法

        //從字節源數組bytes的offset索引位置處開始,截取length長度的子數組,並將子數組按照響應的解碼方法解碼,構建字符串
        // - 如果指定的字符集不受支持 ,拋出異常UnsupportedEncodingException
        // - 如果 offset 和 length 參數索引字符超出 bytes 數組的範圍 , 拋出異常IndexOutOfBoundsException
    
        /**
         *  bytes - 要解碼爲字符的 byte 
            offset - 要解碼的第一個 byte 的索引 
            length - 要解碼的 byte 數 
            charsetName - 受支持 charset 的名稱
         */
        public String(byte[] bytes,
                      int offset,
                      int length,
                      String charsetName)
               throws UnsupportedEncodingException
    
        /**
         *  bytes - 要解碼爲字符的 byte 
            offset - 要解碼的第一個 byte 的索引 
            length - 要解碼的 byte 數 
            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 數
         */
        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
    
  • 小結

    • 通過使用指定的字符集 解碼指定的byte 子數組,構造一個新的 String
    • 編碼方式和解碼方式不一致時,會導致顯示異常,有可能會出現亂碼,如UTF-8編碼,GBK解碼

JS String.from

通過UTF-16 code units

  • 方法

        //有序的UTF-16 code units編碼單元構建,有效範圍時是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—
    
  • 小結

    • 可以直接使用UTF-16 code units 對應的十進制數字,(65, 66, 67)
    • 可以直接使用UTF-16 code units 對應的十六進制數字,十六進制0x2014對應十進制爲8212,輸出結果都爲:
    • 也可以組合使用,只要填入的內容可以轉化爲數字,並且在0~65535範圍內就行
    • 因爲使用的是162進制,即416進制,所以範圍爲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
        Є
        Є
        ?
        ?
    
  • 小結

    • 通過code point構建字符串,沒有範圍0~65535的限制
    • 通過code point構建字符串,可以使用16進制,也可以使用10進制,如?的16進制0x404轉化爲10進製爲1028,輸出結果都爲Є16進制0x2F804轉化爲10進製爲194564,輸出結果都爲?,但是不可以使用字符常量,如'+',會報錯

小結

不同點

  • oc中字符串寫法@""java中字符串寫法""js中字符串寫法""''都可以,一個字符@的區別
  • char基本數據類型,oc中表示1個字節、java表示2個字節
  • bytejava中表示個字節,oc也是個字節,ocByte
  • unicode編碼需要用2個字節表示,oc中用unichar表示,javachar
  • java字符串的構建關係: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爲基礎的,即組成該字符串所需要的unicode unit數目,即需要多少了2字節存儲,ocunicharjavachar

        //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";
    
  • 把字符串源(字節bytes,字符charunicode units)按照指定的編碼方式進行解碼,
    - javacharbytesunicode points
    - occharactersbytesNSDataCStringNSURLfile
    - js: CharCodeCodePoint

  • 通過 unicode 字符構建字符串

    • oc : initWithCharacters ,可以使用 十六進制(如0x2b)十進制數字(如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)十進制數字(如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.fromCodePointString.fromCharCode ,可以使用 十六進制(0x2b)十進制數字(如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
    
  • 小結

    關鍵字都是 length

三、比較 compare

基本概念

  1. 字典排序: 按字典順序比較兩個字符串。該比較基於字符串中各個字符的 Unicode 值。按字典順序將此 String 對象表示的字符序列與參數字符串所表示的字符序列進行比較。如果按字典順序此 String 對象位於參數字符串之,則比較結果爲一個負整數。如果按字典順序此 String 對象位於參數字符串之,則比較結果爲一個正整數。如果這兩個字符串相等,則結果爲 0

OC equalcompare

  • 方法

      //相等判斷
      - (BOOL)isEqualToString:(NSString *)aString;
      //按照unicode編碼順序比較、相等:NSOrderedSame,在前面NSOrderedAscending,在後面NSOrderedDescending
      - (NSComparisonResult)compare:(NSString *)string;
      //忽略大小寫進行比較、'A'和'a'相等
      - (NSComparisonResult)caseInsensitiveCompare:(NSString *)string;
      //比較大小,根據傳入的mask參數
      - (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask;
      //截取調用者range範圍的子字符串和參數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));
    
      //比較結果如下:
      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(@"比較:位於後面");
      }
      //打印結果:
      比較:位於前面
    
    
      NSString *str1 = @"aA";
      NSString *str2 = @"a";
      NSComparisonResult result = [str1 compare:str2];
      if (result == NSOrderedSame) {
          NSLog(@"比較:相等");
      } else if (result == NSOrderedAscending) {
          NSLog(@"比較:位於前面");
      } else {
          NSLog(@"比較:位於後面");
      }
      //輸出:
      比較:位於後面
    
  • 小結

    • 根據mask傳入的參數不同,獲取的結果不一樣;如mask傳入NSCaseInsensitiveSearch,等價於caseInsensitiveCompare:
    • 比較只返回比較結果,不會返回差值

Java equalcompare

  • 方法

      //字典順序比較大小
      public int compareTo(String anotherString)
      //忽略大小寫進行比較
      public int compareToIgnoreCase(String str)
    
      //相等判斷,類型也要相同,爲String類
      public boolean equals(Object anObject) {  }
      //相等判斷,忽略大小寫,'A'和'a'相等
      public boolean equalsIgnoreCase(String anotherString) { }
      //相等判斷,內容相等,類型可能不相同
      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
      相等
    
  • 小結

    • 字符串不同的情況:1、相同索引處的unicode units不同2、長度不同;3、1和2都有
    • 比較的優先級:優先比較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
      位於後面
    
  • 小結

    • 比較只返回比較結果,不會返回差值

小結

  • 相同點
    • 小於:返回負值
    • 相等:返回0
    • 大於:返回正值
  • 不同點

    • jsoc只是單純進行字符串比較,不會返回差值;但是java會返回差值(見?);oc對比較結果進行了封裝,是一個枚舉類型:

      typedef NS_ENUM(NSInteger, NSComparisonResult) {
              NSOrderedAscending = -1L,
              NSOrderedSame, 
              NSOrderedDescending
      };
      
    • ocjava提供了忽略大小寫的比較方法,js沒有直接方法,但是可以先全部轉爲小寫字母(toLowerCase()),然後再進行比較(localeCompare());

四、前綴/後綴 hasPrefixhasSuffixstartsWithendsWith

OC hasPrefixhasSuffix

  • 方法

      // 前綴
      - (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
    
  • 小結

Java startsWithendsWith

  • 方法

      // 前綴
      public boolean startsWith(String prefix)
      // 如果參數表示的字符序列是此對象從索引 toffset 處開始的子字符串前綴,則返回 true;否則返回 false。如果 toffset 爲負或大於此 String 對象的長度,則結果爲 false;否則結果與以下表達式的結果相同:
      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
    
  • 小結

JS startsWithendsWith

  • 方法

      /**
       * “源字符串”的 position 位置(包含)之後的子字符串 是否是以 searchString 開頭的
       * 1、position 表示在 源字符串str 中搜索 searchString 的 “開始位置”,默認值爲 0,也就是真正的字符串開頭處
       */
      str.startsWith(searchString [, position]);
    
      /**
       * “源字符串”的 position 位置(不包含)之後的子字符串 是否是以 searchString 結尾的
       * 1、position 表示在 源字符串str 中搜索 searchString 的結束位置,默認值爲 str.length,也就是真正的字符串結尾處。
       */
      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
    
  • 小結

    • startsWith 前綴判斷,“源字符串” position (包含) 到 length - 1 範圍內的字符串是不是以 searchString 開頭的
    • endsWith 後綴判斷,“源字符串” 0position (不包含) 範圍內的字符串是不是以 searchString 結尾的
    • 先從 “源字符串” 獲取判斷的字符串範圍,然後再進行判斷

小結

  • JavaJS 的關鍵字爲 startsWithendsWithOChasPrefixhasSuffix

五、包含 containsincludes

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
    
  • 小結

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
    
  • 小結

JS includes

  • 方法

      /*
       * 判斷一個字符串是否包含在另一個字符串中,根據情況返回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
    
  • 小結

六、拼接/插入 appendinsertconcat

基本概念

  • oc中的字符串類
    • NSString: 不可變的
    • NSMutableString:可變的
  • Java的字符串類:
    • String: 不可變;
    • StringBuilder:可變的,線程不安全
    • StringBuffer:可變的,線程安全
    • 小結:StringBuilderStringBuffer快,優先使用StringBuilder

OC appendinsertpadding

  • 方法

      //不可變字符串的處理-----------
      //把字符串aString拼接“源字符串”的"末尾"
      - (NSString *)stringByAppendingString:(NSString *)aString;
      //把字符串aString拼接“源字符串”的"末尾",帶有格式的拼接
      - (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;
    
      //可變字符串的處理-----------
      //源字符串“末尾”拼接字符串aString
      - (void)appendString:(NSString *)aString;
      //源字符串“末尾”按照格式拼接字符串
      - (void)appendFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
      //源字符串loc位置處插入字符串aString
      - (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
    
  • 小結

    • NSString不會改變原來字符串的值,會返回一個新的值
    • NSMutableString是對原來字符串進行處理,不會返回新值

Java concatformatappendinsert

  • 方法

      //將指定字符串str拼接到“源字符串”的結尾
      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`
    
  • 小結

    • appendinsert可以看出是format的便捷方法
    • 如果拼接的值爲null,則向該序列中追加 4 個 “null” 字符
    • String類拼接用concatStringBuilder類和StringBuffer類用appendinsert

JS +concatrepeat

  • 方法

      /**
       * 使用加號 + 進行拼接
       */
      +
    
      /**
       * 把 “源字符串” 重複 count 次 得到新的字符串
       * 1、count 範圍爲 [0, +∞),超過範圍會拋出異常 RangeError;count 爲 0 返回空字符串 ''
       */
      str.repeat(count)
    
      /**
       * 在 “源字符串”的基礎上拼接 字符串 string2 、 string3 、 ... stringN
       */
      str.concat(string2, string3[, ..., stringN])
    
  • 例子

      var str = "";
      str += "one";
      console.log(str)
      //輸出:
      one
    
      //重複次數
      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
    
  • 小結

    • js的字符串拼接使用加號+即可
    • repeat(count)count 的範圍爲 [0, +∞) ,超過範圍會拋出異常,count 等於 0 返回空字符串 ''

小結

  • 相同點
    1. ocjava方法的關鍵字爲 appendinsert,java多了concat
    2. ocjava都可以通過格式化字符串format來拼接字符串
  • 不同點
    1. jsjava都可以使用加號+拼接字符串,oc不可以

七、刪除 delete

OC delete

  • 方法

      //刪除“源字符串”range範圍的字符
      - (void)deleteCharactersInRange:(NSRange)range;
    
  • 例子

      NSMutableString *str = [NSMutableString stringWithString:@"hello"];
      [str deleteCharactersInRange:NSMakeRange(1, 2)];
      NSLog(@"%@", str);
      //輸出:
      hlo
    
  • 小結

    • NSMutableString類纔有刪除方法
    • 範圍range超過源字符串範圍時,會crash

Java delete

  • 方法

      //刪除start(包含)到end(不包含)範圍內的字符
      [//end可以>=length,超過length表示一直刪除到字符串尾部](//end可以>=length,超過length表示一直刪除到字符串尾部)
      //如果 start 爲負、大於 length() 或大於 end,會拋出異常StringIndexOutOfBoundsException
      public StringBuilder delete(int start, int end)
    
      //刪除index位置處的字符,此序列將縮短一個 char。
      //注:如果給定索引處的字符是增補字符,則此方法將不會移除整個字符。如果需要準確處理增補字符,那麼可以通過調用 Character.charCount(thisSequence.codePointAt(index))(用此序列取代 thisSequence)來確定要移除的 char 數。
      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
    
  • 小結

    • deletedeleteCharAtStringBuilder類和StringBuffer類纔有的
    • end可以大於等於字符串length,大於等於length會一直刪除掉“源字符串”的末尾
    • 如果 start 爲負、大於 length() 或大於 end,會拋出異常StringIndexOutOfBoundsException
    • deleteCharAt,準確刪除的話需要調用Character.charCount(thisSequence.codePointAt(index)),確定刪除的字符數

JS

  • 參考 替換

小結

  • 相同點

    1. 對於含有emoji字符的字符串,有可能需要3個字節才能表示,但是unicode unit爲2個字節,這時候使用常規的處理會出現問題,需要準確的判斷字符串:

      [//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))`
      
  • 不同點

八、獲取 charcodePointAt

OC characterAtIndex

  • 方法

      /**
       * 獲取 index 位置處的 unicode unit 的數字表示形式
       * 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'
    
  • 小結

Java charAtcodePointAt

  • 方法

      // 返回指定索引處的 char 值。索引範圍爲從 0 到 length() - 1。序列的第一個 char 值位於索引 0 處,第二個位於索引 1 處,依此類推,這類似於數組索引;如果 index 參數爲負或小於此字符串的長度,會拋出異常
      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
    
  • 小結

JS charAtcharCodeAtcodePointAt

  • 方法

      /**
       * 獲取index位置處的 UTF-16 code unit 的字符串形式
       * 1、不填寫參數,默認獲取 0 位置處的字符
       * 2、index 超過 “源字符串” 的範圍,返回空字符串 ""
       */
      character = str.charAt(index)
    
      /**
       * 獲取 index 處 UTF-16 code unit 的 code point 所代表的數字
       * 1、index 超過範圍 返回 NaN
       */
      str.charCodeAt(index)
    
      /**
       * 獲取 index 位置處的 UTF-16 code unit 的 code point 的數字形式
       * 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
    
  • 小結

小結

  • 可以獲取到 index 位置的字符 、代碼點 code point

OC range

  • 方法

      // 查找給定的字符串 ------- 
      // “源字符串” 全部範圍內查找
      - (NSRange)rangeOfString:(NSString *)searchString;
      // “源字符串” 全部範圍內查找,添加一些條件
      - (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask;
      // “源字符串” rangeOfReceiverToSearch 範圍內查找 ,範圍超過 字符串 長度會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}
    
  • 小結

    • 如果查找到返回查找到的範圍,沒有查找到話 rangelength == 0

Java indexOflastIndexOf

  • 方法

      // 在”源字符串“中查找 字符串str 或者 ch代表的Unicode 代碼點代表的字符 ”第一次“ 出現的位置,如果未出現該字符,則返回 -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 代碼點代表的字符 ”最後一次“ 出現的位置,如果未出現該字符,則返回 -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
    
  • 小結

    • indexOf 是按照“從左往右”的順序查找
    • lastIndexOf 是按照“從右往左”的順序查找
    • 查找到則返回所在位置,沒有查找到則返回 -1
  • 方法

      /**
       * 從源字符串的 fromIndex 位置處按照“從左往右”順序查找 searchValue “第一次”出現的位置
       * 1、 fromIndex 是可選值,不填寫值默認從 位置0 開始,小於0(<0)也是從 位置0 開始,超過字符串長度範圍,從length -1 處開始
       * 2、查找到則返回所在位置,沒有查找到則返回 -1
       * 3、該方法是大小寫敏感的
       */
      str.indexOf(searchValue[, fromIndex])
    
      /**
       * 從源字符串的 fromIndex 位置處按照“從右往左”順序查找 searchValue “第一次”出現的位置,
       * 1、 fromIndex 是可選值,不填寫值默認從 位置0 開始,小於0(<0)也是從 位置0 開始,超過字符串長度範圍,從length -1 處開始
       * 2、查找到則返回所在位置,沒有查找到則返回 -1
       */
      str.lastIndexOf(searchValue[, fromIndex])
    
      /**
       * 根據正則表達式查找內容
       * 1、查找到則返回所在位置,沒有查找到則返回 -1
       */
      str.search(regexp)
    
      /*
       * 沒有匹配到返回 null
       * 匹配到返回匹配的結果數組
       */
      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"]
    
  • 小結

    • indexOf 是按照“從左往右”的順序查找
    • lastIndexOf 是按照“從右往左”的順序查找
    • 查找到則返回所在位置,沒有查找到則返回 -1
    • fromIndex 都是按照從左往右計算的

小結

  • JavaJS 的查找位置方法類似(indexOflastIndexOf)、查找到的位置,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範圍內的target字符替換爲replacement,通過options進行相關的控制,如忽略大小寫,傳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;
    
  • 例子

      //“源字符串”的所有範圍內查找,替換
      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範圍內查找,替換
      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範圍內的字符替換爲響應的字符串
      NSString *str = @"hello world";
      NSString *result = [str stringByReplacingCharactersInRange:NSMakeRange(0, 5) withString:@"+"];
      NSLog(@"%@", result);
    
  • 小結

    • 在“源字符”的全部範圍進行查找、替換;- (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查找的內容
      public String replaceAll(String regex, String replacement)
      //用字符串replacement替換掉“第一個”通過正則表達式regex查找的內容
      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
    
  • 小結

JS replace

  • 方法

      /**
       * “源字符”中把查找到的內容(可以是“字符串常量substr”,也可以是“正則表達式regexp”) 用 newSubstr 進行替換
       * ps:
       *      1、不會改變“源字符串”的值
       *      2、替換的是“第一個”查找到的內容
       *      3、如果需要替換“所有”查找到的內容,需要使用正則表達式,加上 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
    
      //正則表達式替換所有查找到的內容
      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
    
    
      //忽略大小寫的,使用真正表達式替換所有查找到的內容
      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
    
  • 小結

    • 替換字符串常量,使用引號"""l"),使用正則表達式,/開始,/結束, 不需要加引號"",(/l/
    • 查找替換全部使用g標誌
    • 忽略大小寫使用i標誌

小結

  • replace 進行替換操作

十一、截取字符串 sub

OC substring

  • 方法

      //包含index位置的內容
      - (NSString *)substringFromIndex:(NSUInteger)from;
      //不包含index位置的內容
      - (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
    

    但是對於顯示的內容需要多個unicode編碼組成的內容(如emoji表情),使用上面的方法會導致emoji表情從中間被截斷,導致內容顯示異常,所以需要使用下面的方法:

      //未處理前--------
      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?
    
  • 小結

    • 可以看到,經過處理之後的字符串截取,避免了字符串的截取位置導致的顯示異常,處理之後的字符串截取結果正常,也符合實際情況;

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
    
  • 小結

    • 如果 beginIndexendIndex,如果 endIndex 大於 length()beginIndex 大於 startIndex , 會拋出異常

JS substringsubstrslice

  • 方法

      /**
       * 截取“源字符串”的 indexStart 位置到 indexEnd 位置的子字符串
       * 1、包含 indexStart 位置字符,不包含 indexEnd 位置字符
       * 2、如果 indexStart 和 indexEnd 相等,返回空字符串 ''
       * 3、如果索引 index 小於 0 或者索引 index 爲 NaN ,則當成 0 處理
       * 4、如果索引 index 大於 length,當成 length  處理
       * 5、參數 indexStart 和 indexEnd ,從這兩者中 較小 的索引位置處開始截取,一直到 較大 的索引位置處,即使 indexStart 大於 indexEnd
       */
      str.substring(indexStart[, indexEnd])
    
      /**
       * 從“源字符串”的 start 位置處開始截取 length 長度的子字符串
       * 1、如果索引 start 小於 0 ,看成是 length + start , 如果 length + start 結果小於 0 ,當成 0 處理
       * 2、如果索引 start 爲 NaN ,則當成 0 處理
       * 3、如果索引 start 大於 length ,返回空字符 ''
       * 4、length 是可選的,如果不傳入參數,默認是 截取到字符串的結尾處
       * 5、如果 length 爲 0 或者 負值,返回空字符串 ''
       */
      str.substr(start[, length])
    
      /**
       * 提取源字符串的 beginSlice(包含) 位置到 endSlice(不包含)位置的字符串
       * 1、如果 beginSlice 或者 endSlice 爲負數,則最終的索引值爲 length + index
       * 2、endSlice 爲負數,可以看成是源字符串從後往前的索引(不包含)
       * 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
    
      ++++++++
    
  • 小結

    1. substring 範圍截取
      • 判斷 indexStartindexEnd ,如果 小於 0 或者爲 NaN ,則當成 0 處理,如果 大於 length ,當成 length 處理
      • indexStartindexEnd較小的位置處開始截取,一直到較大的位置
      • 如果 indexStartindexEnd 相等,返回空字符串''
      • 如果 只有一個參數 indexStart ,則表示從indexStart開始,一直到字符串結尾,等價於 indexStartlength
      • 如果 indexStart 小於 indexEndsubstring(indexStart, indexEnd) 等價於 substring(indexEnd, indexStart) ,如上面的 str.substring(5, 2)str.substring(2, 5)
    2. substr 長度截取
      • 判斷 start 數值,小於 0 ,看成是 length + start , 如果 length + start 結果小於 0 ,當成 0 處理
      • 索引 startNaN ,則當成 0 處理
      • 如果索引 start 大於 length - 1 ,返回空字符 ''
      • length 是可選的,如果不傳入參數,默認是 截取到字符串的結尾
      • 如果 length0 或者 負值,返回空字符串 ''

小結

十二、大小寫 uppercaselowercase

OC uppercaseStringlowercaseStringcapitalizedString

  • 大寫

    @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
    

    地區化

    /* 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 toUpperCasetoLowerCase

  • 大寫

    public String toUpperCase() { }
    
  • 小寫

    public String toLowerCase() { }
    
  • 例子:

    String str = "Hello world";
    Log.d("大小寫", str.toUpperCase());
    Log.d("大小寫", str.toLowerCase());
    
    //打印
    HELLO WORLD
    hello world
    

    地區化

    public String toUpperCase(Locale locale) { }
    public String toLowerCase(Locale locale) { }
    

JS toUpperCasetoLowerCase

  • 大寫

    str.toUpperCase()
    //有返回值,返回值爲"大寫"字母,不會影響原來字符串"str"的值
    
  • 小寫

    str.toLowerCase()
    //有返回值,返回值爲"小寫"字母,不會影響原來字符串"str"的值
    
  • 例子:

    var str = "hello world"
    console.log(str.toUpperCase())
    console.log(str.toLowerCase())
    
    //打印:
    HELLO WORLD
    hello world
    

    地區化:

    str.toLocaleLowerCase()
    str.toLocaleLowerCase(locale) 
    str.toLocaleLowerCase([locale, locale, ...])
    
    str.toLocaleUpperCase()
    str.toLocaleUpperCase(locale) 
    str.toLocaleUpperCase([locale, locale, ...])
    

小結

  • 大寫:uppercase
  • 小寫:lowercase

十三、過濾 trim

OC trim

  • 方法

      // 過濾字符串中的 首尾 在字符結合 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
    
  • 小結

Java trim

  • 方法

      public String trim()
    
  • 例子

      String str = " \r \n  hello \r \n  ";
      String result = str.trim();
      Log.e("過濾", result);
    
      //輸出:
      E/過濾: hello
    
  • 小結

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
    
  • 小結

小結

十四、正則表達式 regexmatch

相關知識

  • 格式 /pattern/flags

  • pattern中符號含義

    • . : 表示除了行結束符(\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 : 表示匹配任意的阿拉伯數字,即 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 : 表示匹配任意的阿拉伯數字,\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 : 表示匹配任意的大寫字母小寫字母阿拉伯數字下劃線\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 : 表示匹配任意的“非” 大寫字母小寫字母阿拉伯數字下劃線\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 字符。不要在此後面跟小數點
    • \cX : XA - Z 的一個字母。匹配字符串中的一個控制字符
    • \xhh : 匹配編碼爲 hh (兩個十六進制數字)的字符
    • \uhhhh : 匹配 Unicode 值爲 hhhh (四個十六進制數字)的字符

      var str = "hello ɀ 013a"
      var result = str.search(/\u0240/)
      var result2 = str.search(/\u0068/) //u0068 對應的字符 爲 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
      
    • $ : 匹配輸入結尾,/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/,以...結尾的單詞;/\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 並且捕獲匹配項結果。 這被稱爲捕獲括號(capturing parentheses)。被匹配的子字符串可以在結果數組的元素 [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)。匹配項不能夠從結果數組的元素 [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’ 都不是匹配結果的一部分。
    • x(?!y) : 只有當 x 後面不是緊跟着 y 時,才匹配 x。例如,/\d+(?!\.)/ 只有當一個數字後面沒有緊跟着一個小數點時,纔會匹配該數字。/\d+(?!\.)/.exec("3.141") 匹配 141 而不是 3.141
    • x|y : 匹配 xy **,例如,/green|red/ 匹配 “green apple” 中的 ‘green‘,”red apple.” 中的 ‘red‘。
    • x{n} : n 是一個正整數。前面的模式 x 連續出現 n 次時匹配
    • x{n,} : n 是一個正整數。前面的模式 x 連續出現至少 n 次時匹配
    • x{n,m} : nm 爲正整數。前面的模式 x 連續出現至少 n 次,至多 m 次時匹配
      • flags中符號含義
    • g : 全局匹配;找到所有匹配,而不是在第一個匹配後停止
    • i : 忽略大小寫
    • m : 多行; 將開始和結束字符(^$)視爲在行上工作(也就是,分別匹配每一行的開始和結束(由 \n\r 分割),而不只是只匹配整個輸入字符串的最開始和最末尾處。
    • u : Unicode; 將模式視爲Unicode序列點的序列
    • y : 粘性匹配; 僅匹配目標字符串中此正則表達式的lastIndex屬性指示的索引(並且不嘗試從任何後續的索引匹配)。

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
    
  • 小結

    • matches 是全局匹配,即整個字符串都是匹配的才返回true,否則返回 false

JS match

  • 方法

      /*
       * 沒有匹配到返回 null
       * 匹配到返回匹配的結果數組
       */
      str.match(regexp)
    
      /**
       * 根據正則表達式查找內容
       * 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"]
    
  • 小結

小結

十五、字符串和其他類型的轉化 parsevalueOf

OC

  • 字符串轉數字等

      @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));
    
  • 數字等轉字符串

      - (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

  • 字符串轉數字等

      public static Integer valueOf(String s)
      .... 依次類推
    
  • 數字等轉字符串

      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 parseIntparseFloattoString+

  • 字符串轉數字

    • 方法

      /**
       * 把字符串 string 轉化爲 radix 進制的整數數值,返回值爲 整數number 或 NaN
       * 1、要明確給出radix參數的值
       * 2、在沒有指定基數,或者基數爲 0 的情況下,JavaScript 作如下處理:
       *   - 如果字符串 string 以"0x"或者"0X"開頭, 則基數是16 (16進制).
       *   - 如果字符串 string 以"0"開頭, 基數是8(八進制)或者10(十進制),那麼具體是哪個基數由實現環境決定。ECMAScript 5 規定使用10,但是並不是所有的瀏覽器都遵循這個規定。因此,永遠都要明確給出radix參數的值。
       *   - 如果字符串 string 以其它任何值開頭,則基數是10 (十進制)。
       */
      parseInt(string, radix);
      
      /**
       * 把字符串 string 轉化爲 radix 進制的小數數值,返回值爲 小數number 或 NaN
       */
      parseFloat(string)
      
    • 例子

      console.log(parseInt('0Xa0'))
      console.log(parseInt('010'))
      console.log(parseInt('08'))
      console.log(parseInt('20'))
      
      //輸出:
      160
      10
      8
      20
      
    • 小結

      • 參數 radix 需要指定,防止一些不必要的錯誤
      • 當無法轉化爲數字時,返回NaN
  • 數字轉字符串

    • 方法

      /**
       * 把數字轉化爲 radix進制的字符串形式
       * 1、radix :可選值,不傳默認爲10進制
       * 2、radix :取值 2-36 之間的整數,其他會拋出異常RangeError
       */
      numObj.toString([radix])
      
      //使用加號+拼接 
      '' + number
      
    • 例子

      var num = 123;
      console.log(num.toString());
      console.log('' + 123);
      
      //輸出:
      123
      123
      
    • 小結

十六、分割字符串爲數組 Separatedsplit

OC Separated

  • 方法

      // 根據 指定的字符串 separator 進行分割
      - (NSArray<NSString *> *)componentsSeparatedByString:(NSString *)separator;
      // 根據 指定的字符集合 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 ",
          "",
          "",
          ""
      )
    
  • 小結

    • componentsSeparatedByString 是根據給定的字符串進行分割
    • componentsSeparatedByCharactersInSet 是根據給定的字符集合分割,查找到一個符合的字符就當成是一個分隔符進行分割,如上面的例子中 1231 進行分割一次得到 hello2 進行分割一次得到 ""3 進行分割一次得到 ""

Java split

  • 方法

      // 根據正則表達式 regex 分割字符串
      public String[] split(String regex)
      // 根據正則表達式 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
    
  • 小結

    • 會過濾最後的空字符 ""

JS split

  • 方法

      /**
       * 把字符串根據指定的分隔符 separator 進行分割字符串,返回字符串數組前 limit 個元素組成的子數組
       * 1、separator 可以是 字符串常量 或者 正則表達式
       * 2、對於正則表達式,如果需要返回匹配到的內容,需要加掛號 ()
       * 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 ", ""]
      //因爲最後一個是數字,所以分割後的字符串數組,最後一個元素爲空字符串
    
      var result4 = str.split(/(\d+)/);
      console.log(result4);
      //輸出: ["hello ", "123", " world ", "456", " nice ", "987", ""]
    
  • 小結

    • 根據 字符串常量正則表達式 進行分割
    • 如果字符串的第一個或者最後一個 和 分隔符匹配,也會進行分割,元素是空字符串 ""

小結

  • jsoc 分割不會過濾最後的空字符 ""java 分割會過濾最後的空字符 ""

十七、編碼

OC

概念

  • OC中的字符串NSSring是由有序UTF-16編碼的”單元“(code unitscharacters)組成的
  • 長度length、索引index,範圍range都是基於字符串的UTF-16的編碼”單元”處理和操作的
  • “單元”code unitsunichar類型表示(無符號的short類型,typedef unsigned short unichar),2字節,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個字節表示code point
      NSUnicodeStringEncoding : Unicode編碼,國際統一的,2個字節表示一個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;

字節大小

  • 方法

        //是否可以轉化爲相應的編碼方式
        - (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding;
        //“預估”轉化爲enc編碼方式的所佔的字節大小
        - (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc;  // Result in O(1) time; the estimate may be way over what's needed. Returns 0 on error (overflow)
        //“準確”計算轉化爲enc編碼方式所佔的字節大小
        - (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 points8位(1個字節byte)表示;UTF-16編碼方式,一個單元code points16位(2個字節byte)表示,所以纔有了?的輸出結果,UTF-16編碼方式的字節數長度是UTF-8的兩倍

字符串和二進制數據的轉化

  • 方法

      [//NSSring](//nssring) 轉 NSData 
      - (nullable NSData *)dataUsingEncoding:(NSStringEncoding)encoding allowLossyConversion:(BOOL)lossy;  
      - (nullable NSData *)dataUsingEncoding:(NSStringEncoding)encoding;                                  
    
      //NSData 轉 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語言字符串的轉化

  • 方法

      //oc字符串轉c字符串--------
      //轉化爲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字符串轉oc字符串--------
      //c字符串cString通過enc編碼方式轉爲oc字符串
      - (nullable instancetype)initWithCString:(const char *)nullTerminatedCString encoding:(NSStringEncoding)encoding;
      + (nullable instancetype)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc;
      //c字符串nullTerminatedCString轉化爲UTF-8編碼方式的oc字符串
      - (nullable instancetype)initWithUTF8String:(const char *)nullTerminatedCString;
      + (nullable instancetype)stringWithUTF8String:(const char *)nullTerminatedCString;
    
  • 例子

      //oc字符串轉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字符串轉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位編碼,會導致結果錯誤;

字符串和字節的轉化

十八、保存到文件

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;
    
  • 例子

  • 小結

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章