Search code examples
c++objective-carraysnsstringcopying

Putting String into a 2D Matrix in Objective C++


So I'm using Objective C++ and I want to put a string into a 4 by X (X = length of string/4) int array by using the ASCII code. The first quarter of the string (which is formatted to fit completely into a 4 by X array) is supposed to go in [0][col], the second quarter into [1][col], the third quarter into [2][col] and the fourth quarter into [3][col]. So I tried the following with 4 for loops, but it doesnt work at all, and I just can't seem to get it to work somehow. Any suggestions would be greatly appreciated.

textMatrix is the matrix in which I want to put the NSString/ASCII number, and inputFinal is the NSString itself. Length * (1/4) or whatever is also always going to be an integer.

for(int i = 0; i < length*(1/4); i++)
{
    textMatrix[0][i] = (int)[inputFinal characterAtIndex: i];
}
for(int j = length*(1/4); j < length*(2/4); j++)
{
    textMatrix[1][j] = (int)[inputFinal characterAtIndex: j];

}
for(int k = length*(2/4); k < length*(3/4); k++)
{
    textMatrix[2][k] = (int)[inputFinal characterAtIndex: k];
}
for(int l = length*(3/4); l < length; l++)
{
    textMatrix[3][l] = (int)[inputFinal characterAtIndex: l];
}

Solution

  • actually a double loop like so ended up working best for me:

    int index = 0;
    for(int row = 0; row < 4; row++)
    {
        for(int col = 0; col < length/4; col++)
        {
            textMatrix[row][col] = (int)[inputFinal characterAtIndex:index];
            index++;
        }
    }