-4

我喜欢将字符串标记为字符并将标记存储在字符串数组中。我正在尝试使用以下无法正常工作的代码,因为我正在使用 C 表示法来访问数组。需要改变什么来代替旅行路径[i]?

NSArray *tokanizedTravelPath= [[NSArray alloc]init];
for (int i=0; [travelPath length]; i++) {
    tokanizedTravelPath[i]= [travelPath characterAtIndex:i];
4

3 回答 3

1

您需要一个 NSMutableArray 来设置数组的每个元素(否则您无法更改其对象)。此外,您只能在数组中插入对象,因此您可以:
- 插入包含字符的 NSString;
- 改用 C 风格的数组。
这是如何使用 NSMutableArray:

NSMutableArray *tokanizedTravelPath= [[NSMutableArray alloc]init];
for (int i=0; i<[travelPath length]; i++) 
{
    [tokanizedTravelPath insertObject: [NSString stringWithFormat: @"%c", [travelPath characterAtIndex:i]] atIndex: i];
}
于 2012-09-18T01:49:37.243 回答
1

您不能将unichars 存储在NSArray*. 你到底想完成什么?AnNSString*已经是 s 集合的一个很好的表示unichar,并且您已经拥有其中一个。

于 2012-09-18T01:50:06.047 回答
1

I count 3 errors in your code, I explain them at the end of my answer.
First I want to show you a better approach to split a sting into it characters.


While I agree with Kevin that an NSString is a great representation of unicode characters already, you can use this block-based code to split it into substrings and save it to an array.

Form the docs:

enumerateSubstringsInRange:options:usingBlock:
Enumerates the substrings of the specified type in the specified range of the string.

NSString *hwlloWord = @"Hello World";
NSMutableArray *charArray = [NSMutableArray array];
[hwlloWord enumerateSubstringsInRange:NSMakeRange(0, [hwlloWord length])
                              options:NSStringEnumerationByComposedCharacterSequences
                           usingBlock:^(NSString *substring,
                                        NSRange substringRange,
                                        NSRange enclosingRange,
                                        BOOL *stop)
{
    [charArray addObject:substring];
}];
NSLog(@"%@", charArray);

Output:

(
    H,
    e,
    l,
    l,
    o,
    " ",
    W,
    o,
    r,
    l,
    d
)

But actually your problems are of another nature:

  • An NSArray is immutable. Once instantiated, it cannot be altered. For mutable array, you use the NSArray subclass NSMutableArray.

  • Also, characterAtIndex does not return an object, but a primitive type — but those can't be saved to an NSArray. You have to wrap it into an NSString or some other representation.

    You could use substringWithRange instead.

    NSMutableArray *tokanizedTravelPath= [NSMutableArray array];
    for (int i=0; i < [hwlloWord length]; ++i) {
        NSLog(@"%@",[hwlloWord substringWithRange:NSMakeRange(i, 1)]);
        [tokanizedTravelPath addObject:[hwlloWord substringWithRange:NSMakeRange(i, 1)]];
    }
    
  • Also your for-loop is wrong, the for-loop condition is not correct. it must be for (int i=0; i < [travelPath length]; i++)

于 2012-09-18T02:00:55.167 回答