问题
How I can split a string into equal parts and not a character, ie, a string that is 20 characters divided into 5 strings with 2 characters each no matter what kind of character is?
don't work to me [NSString componentsSeparatedByString]: because the characters change randomly.
i'm using objetive-c on xcode 5
回答1:
This is just an example of what you're probably looking to do. This method assumes the length of the string is evenly divisible by the intended substring length, so having a test string with 20 characters and a substring length of 2, will produce an array with 10 substrings with 2 characters in each. If the test string is 21 characters the 21st char will be ignored. Once again, this is not THE way to do exactly what you want to do (which still isn't totally clear), but it is merely a demonstration of something similar to what you may want to be doing:
// create our test substring (20 chars long)
NSString *testString = @"abcdefghijklmnopqrstu";
// our starting point will begin at 0
NSInteger startingPoint = 0;
// each substring will be 2 characters long
NSInteger substringLength = 2;
// create our empty mutable array
NSMutableArray *substringArray = [NSMutableArray array];
// loop through the array as many times as the substring length fits into the test
// string
for (NSInteger i = 0; i < testString.length / substringLength; i++) {
// get the substring of the test string starting at the starting point, with the intended substring length
NSString *substring = [testString substringWithRange:NSMakeRange(startingPoint, substringLength)];
// add it to the array
[substringArray addObject:substring];
// increment the starting point by the amount of the substring length, so next iteration we
// will start after the last character we left off at
startingPoint += substringLength;
}
The above produced this:
2014-08-23 15:33:41.662 NewTesting[49723:60b] ( ab, cd, ef, gh, ij, kl, mn, op, qr, st )
来源:https://stackoverflow.com/questions/25465420/how-split-a-string-by-equial-parts