2

この質問の前に、お詫びをさせてください。私は Objective C に非常に慣れていません。残念ながら、仕事のプロジェクトのタイムラインが非常にタイトで、できるだけ早くスピードアップする必要があります。

以下のコードは機能します。これを処理するためのより良い方法があるかどうか疑問に思っています...おそらくもっとココアっぽいものです。関数の全体的な目的は、特定の値を持つ文字列内の位置の順序付きリストを取得することです。

快適さの理由から、標準の配列に戻りました。最初に宣言する NSMutableString は、テスト目的のみです。この言語の完全な初心者であり、Objective C (および私が推測する C++) が変数とポインターを処理する方法に頭を悩ませています。あらゆるヒント、ヒント、ポインターを歓迎します。

NSMutableString *mut = [[NSMutableString alloc] initWithString:@"This is a test of the emergency broadcast system.  This is only a test."];

NSMutableArray *tList = [NSMutableArray arrayWithArray:[mut componentsSeparatedByString:@" "]];

int dump[(tList.count-1)];
int dpCount=0;
NSUInteger length = [mut length];
NSRange myRange = NSMakeRange(0, length);

while (myRange.location != NSNotFound) {

    myRange = [mut rangeOfString:@" " options: 0 range:myRange];

    if (myRange.location != NSNotFound) {
        dump[dpCount]=myRange.location;
        ++dpCount;
        myRange = NSMakeRange((myRange.location+myRange.length), (length - (myRange.location+myRange.length)));
    }
}

for (int i=0; i < dpCount; ++i) {
    //Going to do something with these values in the future... they MUST be in order.
    NSLog(@"Dumping positions in order: %i",dump[i]);
}
text2.text = mut;
[mut release];

返信ありがとうございます。

4

2 に答える 2

1

これはもう少し合理化されるかもしれません(そしてそれが重要な場合は実行時間の点でより速くなります):

const char *p = "This is a test of the emergency broadcast system.  This is only a test.";
NSMutableArray *positions = [NSMutableArray array];

for (int i = 0; *p; p++, i++)
{
    if (*p == ' ') {
        [positions addObject:[NSNumber numberWithInt:i]];
    }
}

for (int j = 0; j < [positions count]; j++) {
    NSLog(@"position %d: %@", j + 1, [positions objectAtIndex:j]);
}
于 2012-05-16T00:20:41.690 に答える
1

あなたがやろうとしていることを行う素晴らしい方法はありません。1 つの方法を次に示します。

// locations will be an NSArray of NSNumbers -- 
// each NSNumber containing one location of the substring):
NSMutableArray *locations = [NSMutableArray new];
NSRange searchRange = NSMakeRange(0,string.length);
NSRange foundRange;
while (searchRange.location < string.length) {
    searchRange.length = string.length-searchRange.location;
    foundRange = [string rangeOfString:substring options:nil range:searchRange];
    if(foundRange.location == NSNotFound) break;
    [locations addObject:[NSNumber numberWithInt:searchRange.location]];
    searchRange.location = foundRange.location+foundRange.length;
}
于 2012-05-15T23:31:20.460 に答える