如何在 iOS 上将字符串拆分为子字符串?

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

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

How to split string into substrings on iOS?

iosobjective-ciphonestringsubstring

提问by Chilly Zhong

I received an NSStringfrom the server. Now I want to split it into the substring which I need. How to split the string?

NSString从服务器收到了一个。现在我想把它拆分成我需要的子串。如何拆分字符串?

For example:

例如:

substring1:read from the second character to 5th character

substring1:从第二个字符读取到第5个字符

substring2:read 10 characters from the 6th character.

substring2:从第 6 个字符开始读取 10 个字符。

回答by codelogic

You can also split a string by a substring, using NString's componentsSeparatedByStringmethod.

您还可以使用 NString 的componentsSeparatedByString方法按子字符串拆分字符串。

Example from documentation:

文档中的示例:

NSString *list = @"Norman, Stanley, Fletcher";
NSArray *listItems = [list componentsSeparatedByString:@", "];

回答by Joel Levin

NSString has a few methods for this:

NSString 为此提供了一些方法:

[myString substringToIndex:index];
[myString substringFromIndex:index];
[myString substringWithRange:range];

Check the documentation for NSString for more information.

查看 NSString 的文档以获取更多信息。

回答by ben

I wrote a little method to split strings in a specified amount of parts. Note that it only supports single separator characters. But I think it is an efficient way to split a NSString.

我写了一个小方法来将字符串分成指定数量的部分。请注意,它仅支持单分隔符。但我认为这是拆分 NSString 的有效方法。

//split string into given number of parts
-(NSArray*)splitString:(NSString*)string withDelimiter:(NSString*)delimiter inParts:(int)parts{
    NSMutableArray* array = [NSMutableArray array];

    NSUInteger len = [string length];
    unichar buffer[len+1];

    //put separator in buffer
    unichar separator[1];
    [delimiter getCharacters:separator range:NSMakeRange(0, 1)];

    [string getCharacters:buffer range:NSMakeRange(0, len)];

    int startPosition = 0;
    int length = 0;
    for(int i = 0; i < len; i++) {

        //if array is parts-1 and the character was found add it to array
        if (buffer[i]==separator[0] && array.count < parts-1) {
            if (length>0) {
                [array addObject:[string substringWithRange:NSMakeRange(startPosition, length)]];

            }

            startPosition += length+1;
            length = 0;

            if (array.count >= parts-1) {
                break;
            }

        }else{
            length++;
        }

    }

    //add the last part of the string to the array
    [array addObject:[string substringFromIndex:startPosition]];

    return array;
}