Question

I can sum up strings:

result=[firstString stringByAppendingString:secondString];

I can subtract one string from another:

result=[firstString stringByReplacingOccurencesOfString:secondString withString:@""];

Can you help me to divide a string into equal strings (e.g. i have string @"Qwerty", i want to divide it by 3 and get array @[@"Qw",@"er",@"ty"], or divide it by 2 to get @[@"Qwe",@"rty"])? Thanks!

Was it helpful?

Solution

You can get the string length divide it by desired number and base of it create NSRange:

    NSString *str = @"Qwerty";
    int len = str.length;
    int devider = 2; // Change it to control result length

    for (int i = 0; i < len; i += devider)
    {
        // You should do some validation to make sure your location and length is in range f string length
        NSRange ran = NSMakeRange(i, devider);
        NSString *res = [str substringWithRange:ran];
        NSLog(@"res: %@", res);
    }

You can create NSString category to achieve the result you are asking for. Hope this help.

OTHER TIPS

Please use function [NSString substringWithRange:]. More info here.

Yes David, Hearing You...!!!

Bellow is the code.

for(int i=0;i<strToDivide.length-iLengthToDivide;i=i+iLengthToDivide)
{
NSString *strPart=[strToDivide substringWithRange:(i,iLengthToDivide)];

[arrToStoreParts addObject:strPart];

//if the length of string is not perfectly divisible by iLengthToDivide
  if(i+iLengthToDivide>strToDivide.length)
 {
 strPart=[strToDivide substringWithRange:(i,strToDivide.length-i)];
 [arrToStoreParts addObject:strPart];
 }
strPart=nil;
}
}

arrToStoreParts will contain all strings came in resultset.

I thought bundling this function in a for loop is pretty easy and he would be able to do that as he is aware of other string functions so didn't give code initially. Hope it helps though :)

NSMutableArray* array1 = [[NSMutableArray alloc] init];

int divide_factor = <your divide_factor>;

while (yourString.length) {

    NSString* substring = [yourString substringWithRange:NSMakeRange(0, MIN(divide_factor, yourString.length))];

    [array1 addObject:substring];

    yourString = [yourString stringByReplacingCharactersInRange:NSMakeRange(0, MIN(divide_factor, yourString.length)) withString:@""];

}

The advantage is that, irrespective of the length of string, it does not throw any exceptions. The last substring will be the leftover substring after division.

TEST CASES:

(1)

yourString = @"abcdefghijklmnopqrstuvwxyz";

divide_factor = 3;

Then results is: ( abc, def, ghi, jkl, mno, pqr, stu, vwx, yz )

(2)

yourString = @"abcdefghijklmnopqrstuvwxyz";

divide_factor = 7;

result: ( abcdefg, hijklmn, opqrstu, vwxyz )

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top