2009-12-09 64 views
-1

我有一个int,由于某种原因它不工作后16左右。这里是我的代码:cocoa:NSString不删除所有字符

NSArray *sortedArray; 
sortedArray = [doesntContainAnother sortedArrayUsingFunction:firstNumSort context:NULL]; 

int count2 = [sortedArray count]; 
//NSLog(@"%d", count2); 
int z = 0; 
while (z < count2) { 
    NSString *myString = [sortedArray objectAtIndex:z]; 
    NSString *intstring = [NSString stringWithFormat:@"%d", z]; 
    NSString *stringWithoutSpaces; 
    stringWithoutSpaces = [[myString stringByReplacingOccurrencesOfString:intstring 
                   withString:@""] mutableCopy]; 
    [hopefulfinal addObject:stringWithoutSpaces]; 
    NSLog(@"%@", [hopefulfinal objectAtIndex:z]); 
    z++; 
} 

编辑:这不是int,这是stringWithoutSpaces线...我无法弄清楚什么导致了它。

所以它(的NSLog,看到的Z ++以上)看起来是这样的:

“这里的”

“无所谓”

“17 whatevere”

“18本”

+0

也许你可以告诉我们你有什么(你的输入数据)和你想达到什么目的。 – stefanB 2009-12-09 03:25:07

+0

根据我对你的代码的理解,你正在将char转换为一个ascii值的字符串,然后我不确定你要替换什么,因为该行不完整。 – stefanB 2009-12-09 03:29:01

+0

你为什么做一个可变的副本?你不要改变字符串。另外,你泄漏它。 – 2009-12-09 06:45:31

回答

2

我猜这与你早些时候有关问题Sort NSArray’s by an int contained in the array,那你要剥去一个数组,看起来像一个你在这个问题有领先的数字和空格:

"0 Here is an object" 
"1 What the heck, here's another!" 
"2 Let's put 2 here too!" 
"3 Let's put this one right here" 
"4 Here's another object" 

不知道全情投入,我猜你的代码可能会失败,因为领先的数字和z的值不同步。由于您似乎并不关心前面的数字是什么,只是想要将它缩小,我建议采用不同的方法来扫描前导数字并从这些数字结束的位置提取子字符串:

NSArray *array = [NSArray arrayWithObjects:@"1 One", 
              @"2 Two", 
              @"5 Five", 
              @"17 Seventeen", 
              nil]; 

NSMutableArray *results = [NSMutableArray array]; 
NSScanner *scanner; 
NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet]; 

for (NSString *item in array) { 
    scanner = [NSScanner scannerWithString:item]; 
    [scanner scanInteger:NULL]; // throwing away the BOOL return value... 
           // if string does not start with a number, 
           // the scanLocation will be 0, which is good. 
    [results addObject:[[item substringFromIndex:[scanner scanLocation]] 
         stringByTrimmingCharactersInSet:whitespace]]; 
} 

NSLog(@"Resulting array is: %@", results); 

// Resulting array is: (
// One, 
// Two, 
// Five, 
// Seventeen 
//) 

+0

谢谢,它完美的作品~~~~~ – 2009-12-09 16:24:57