7

Does anyone know how to do this, I want to put a variable inside a string:

currently using:

 oraclizeID = oraclize_query("URL","json(https://opensky-network.org/api/states/all?icao24=a4dad4).states[0][8]");

Trying to put the varaible into the string as shown below, but it's not working:

string public id = 'a4dad4';
oraclizeID = oraclize_query("URL","json(https://opensky-network.org/api/states/all?icao24="id").states[0][0]")
Achala Dissanayake
  • 5,819
  • 15
  • 28
  • 38
Simon Mullaney
  • 231
  • 1
  • 2
  • 7

2 Answers2

4

This would work if you do string concatenation. You may refer this question for string concatenation in solidity. The code may look like follow for string concatenation.

url_1 = "json(https://opensky-network.org/api/states/all?icao24";
url_2 = id;
url_3 = ")states[0][0]"

bytes memory burl_1 = bytes(url_1);
bytes memory burl_2 = bytes(url_2);
bytes memory burl_3 = bytes(url_3);

string memory url = string(burl_1.length + burl_2.length + burl_3.length);
bytes memory burl = bytes(url);

uint k = 0;
for (uint i = 0; i < burl_1.length; i++) burl[k++] = burl_1[i];
for (i = 0; i < burl_2.length; i++) burl[k++] = burl_2[i];
for (i = 0; i < burl_3.length; i++) burl[k++] = burl_3[i];

url = string(burl);
Monkleys
  • 3
  • 1
Achala Dissanayake
  • 5,819
  • 15
  • 28
  • 38
  • Where did the variable burl come from? – John DeBord May 23 '18 at 00:21
  • And I'm getting the error: TypeError: Exactly one argument expected for explicit type conversion. string memory query = string( burl_1.length, burl_2.length, burl_3.length, burl_4.length, burl_5.length, burl_6.length, burl_7.length); – John DeBord May 23 '18 at 00:33
  • Hi @JohnDeBord, you have to first declare byte memory burl = bytes(url); and for the second error it should be + not , needed. I'll correct them in the example – Achala Dissanayake May 23 '18 at 00:37
  • 2
    sorry @AchalaDissanayake thought I could accept both - I just undid it :) – Simon Mullaney May 23 '18 at 07:57
4

As the accepted answer says, this is basically a string concatenation problem. Sometimes using library for that might be efficient as some answers suggested here.

ETHER
  • 180
  • 2
  • 13