10 years ago.

Splitting a string

I get an string from lab view for example 100907 this string is the information to control 3 pmw´s the first is 10, the second 09, the third 07 , i need to know how to split them apart and then allocate them in variables so i can convert them into integers.

2 Answers

10 years ago.

A quick stab ?

assuming you have the 'string' in a buffer, then you could something like this ..

int a, b, c;

// buffer contains '100907' 

a = ((buffer[0] & 0x30) * 100) + (buffer[1] & 0x30);
b = ((buffer[2] & 0x30) * 100) + (buffer[3] & 0x30);
c = ((buffer[4] & 0x30) * 100) + (buffer[5] & 0x30);

but for a more elegant solution, get Lab View to send 10 09 07,

and use Lab-View Example

Hope that was usefull ..

Ceri

Accepted Answer
10 years ago.

Ceri's answer looks along the right lines but it should be - 0x30 not & 0x30 and *10 not *100. & 0x30 will give you a result of 0x30 for all digits.

A more generic version would be:

unsigned int CharArrayToInt(char *firstDigit, int numberOfDigits) {

  unsigned int total = 0;
  int digit = 0;

  while (digit < numberOfDigits) {  // loop until all digits have been done
    total *= 10;  // move everything to the left by one digit
    total +=   *(firstDigit + digit) - 0x30; // add the next digit. 0 = ascii 0x30, 1 = 0x31 etc...
    digit++;
  }

  return total;
}

main () {
.....

unsigned int a = CharArrayToInt(buffer,2);
unsigned int b = CharArrayToInt(buffer+2,2);
unsigned int c = CharArrayToInt(buffer+4,2);
....
}

This way if you have a 3 digit number (or 1 digit) at some point then you can use exactly the same code and just tell the conversion function the correct number of digits.

Note there is no protection stopping you from reading beyond the end of the array if you give invalid parameters. Nor is there any sanity checking, if you give it something that contains characters other than 0 to 9 you'll get weird results.