【问题标题】:How to split a string of words and add to an array - Objective C如何拆分一串单词并添加到数组中 - Objective C
【发布时间】:2012-07-04 18:32:38
【问题描述】:

假设我有这个:

NSString *str = @"This is a sample string";

我将如何拆分字符串以将每个单词添加到 NSMutableArray 中?

在 VB.net 中你可以这样做:

Dim str As String
    Dim strArr() As String
    Dim count As Integer
    str = "vb.net split test"
    strArr = str.Split(" ")
    For count = 0 To strArr.Length - 1
        MsgBox(strArr(count))
    Next

那么如何在 Objective-C 中做到这一点?谢谢

【问题讨论】:

标签: objective-c string


【解决方案1】:

工作解决方案。试试看!

NSString *string = @"This is words";
NSArray *wordsArray  = [string componentsSeparatedByString:@" "];

让我们打印 wordsArray 的值。

NSlog(@"wordsArray value is : %@", wordsArray);

这是输出:

wordsArray value is : (
    This,
    is,
    words
)

【讨论】:

    【解决方案2】:
    NSArray *words = [str componentsSeparatedByString: @" "];
    

    请注意,words 作为自动释放对象返回,因此您可能需要 retain 它,除非您使用的是 ARC。

    此外,返回的数组是不可变的,因此您需要自己创建一个并使用返回的数组对其进行初始化:

    NSArray *words = [str componentsSeparatedByString: @" "];
    NSMutableArray *mutableWords = [NSMutableArray arrayWithCapacity:[words count]];
    [mutableWords addObjectsFromArray:words];
    

    或:

    NSMutableArray *mutableWords = [[str componentsSeparatedByString: @" "] mutableCopy];
    

    最后一条语句返回一个必须释放的对象,copy 为您提供该对象的所有权。

    【讨论】:

    • 如果我不仅要按空格,还要按逗号、句点等一些字符来分割字符串,该怎么办?
    • @user1412469 只需将@" " 更改为@","@"." 等。
    • 不,我的意思是,像NSString *str = @"This string is separated by space, comma, and period. How to separate it?" 这样的单个字符串,我该怎么做?或者你的意思是我会重复NSArray *words = [str componentsSeparatedByString: ]; 三次,用不同的组件。
    • @user1412469 恐怕是这样,但是您可以在分隔符字符串中使用多个字符,例如 @", "
    • @user1412469 您最好用空格分隔,然后从返回的数组中的每个元素中去掉前导和尾随逗号或点。
    【解决方案3】:

    NSString 上有一个内置方法,它根据您传入的一组字符拆分字符串并返回一个 NSArray

    - (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
    

    如需了解更多信息,请参阅NSString class reference

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多