Wondering if its possible to convert between string memory and string calldata in order to use indexing of the form string[start : end] which only works string calldata. This function seems to works:
function splice(string calldata source, int startPos, int numchars) public pure returns(string memory) {
if (startPos > int(length(sourcestring))) return "";
int start = startPos -1;
int end = startPos + (numchars -1);
string memory retval = string(source[uint(start) : uint(end)]);
return retval;
}
but if I change the parameter source to string memory, then I get an error on
string memory retval = string(source([uint(start) : uint(end)])
because apparently the form sourcestring[start : end] to get a substring works on calldata strings not on memory strings, and there is no obvious way to convert a string memory to a string calldata.
Is there any means to do this?
Calldata is read-only. You can decode calldata variables into memory but not the other way around.
Unfortunately array slicing is only implemented for calldata. For memory and storage it's a bit more complicated and has not been implemented yet (see issue #7423).
The workaround in your case is to copy the characters one by one, which is really what the compiler would do under the hood anyway since you're trying to return the slice from a public function (which would materialize the slice into an array).
Probably not since calldata is for data supplied while making an external transaction. Very different purpose compared to storage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With