Question

Hi i'm trying to get to NSStrings to equal each other in length for a project of mine but i'm seem to be having trouble. I got two string

    NSString *word1=@"123456";
    NSString *word2=@"123";

I hard coded them to be different lengths for other testing.I'm trying to append 0s at the from of word to so it'll look like @"000123" and i tried this method to append the string but instead it builds up ram and if i leave the program running long enough my system crashes..any help on how to fix this? is there a different method to doing this?

    while ([word1 length]>[word2 length]){
        [word2 stringByAppendingString:@"0"];
    }
    while ([word1 length]<[word2 length]){
        [word1 stringByAppendingString:@"0"];
    }
Était-ce utile?

La solution

You are not changing the strings. NSString objects are immutable, you either have to assign the result:

word2 = [word2 stringByAppendingString:@"0"];

or use NSMutableString and appendString:

[word2 appendString:@"0"];


You also have to reverse your logic, as "append" means "add to the end".

append |əˈpɛnd| verb [ with obj. ] add (something) to the end of a written document: the results of the survey are appended to this chapter.

Autres conseils

You need to change your code to this

while ([word1 length]>[word2 length]){
        word2 = [word2 stringByAppendingString:@"0"];
}
while ([word1 length]<[word2 length]){
        word1 = [word1 stringByAppendingString:@"0"];
}

I think the reason for the memory increase and app crash is because you are having an infinite loop in your old code. Try putting NSLog into the while loop in your old code and see what is the output. The code I suggested should not have such problem.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top