-4

文字列を文字にトークン化し、トークンを文字列配列に格納するのが好きです。C表記を使用して配列にアクセスしているため、機能しない次のコードを使用しようとしています。travel path[i] の代わりに何を変更する必要がありますか?

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

3 に答える 3

1

配列のすべての要素を設定するには、NSMutableArray が必要です (そうしないと、そのオブジェクトを変更できません)。また、配列にはオブジェクトしか挿入できないため、次のことができます

- 代わりに 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

unicharに s を格納することはできませんNSArray*。正確に何を達成しようとしていますか?AnNSString*はすでに のコレクションの優れた表現でありunichar、それらの 1 つを既に持っています。

于 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 に答える