2

I would like to replace a letter at a specific position of a string with another letter.

function _stringReplace(string memory _string, uint256 _pos, string memory _letter) internal pure returns (string memory) {
1

Solidity doesn't manage strings but you can use this function I've written for you :

 function _stringReplace(string memory _string, uint256 _pos, string memory _letter) internal pure returns (string memory) {
        bytes memory _stringBytes = bytes(_string);
        bytes memory result = new bytes(_stringBytes.length);

  for(uint i = 0; i < _stringBytes.length; i++) {
        result[i] = _stringBytes[i];
        if(i==_pos)
         result[i]=bytes(_letter)[0];
    }
    return  string(result);
 } 

if you call it for example with "hello",0,"y" will return "yello" enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.