A similar question has been asked but using web3 in java, however, I would like to encode a string
to bytes[]
in solidity itself.
1 Answer
Supposing your string comes from an external source (someone outside your contract calls the function with such string as a parameter) you can cast it to bytes and then slice the bytes into an array. Something like this.
contract Cast {
bytes [] public arr;
function convertExternalString(string calldata str) external{
bytes calldata bts =bytes(str);
for(uint i; i<bts.length; i++){
arr.push(bts[i:i+1]);
}
}
}
Now, if your string is stored on the contract you can also convert it but would have to change the visibility of the function convertExternalString
to public
and then call it with a this.
. The next code works.
contract Cast {
bytes [] public arr;
string public st = "Hello";
function convertInternalString() public {
this.convertExternalString(st);
}
function convertExternalString(string calldata str) public {
bytes calldata bts =bytes(str);
for(uint i; i<bts.length; i++){
arr.push(bts[i:i+1]);
}
}
}
Note that calldata slicing is only available for solidity 0.6.0 and above.
string
tobytes[]
? I guess what you are really looking for isstring
tobytes
?