2

I am learning solidity string/byte manipulation and I am trying to create a Solidity function that finds specific words in a string/format and replaces them with given variables to return "edited" string

Example:

string format = "UserData: {address}, {balance}"

function replaceWords(string calldata Format) external pure returns (string memory){

   address addr = 0x8599fed66e2a440f12e9bc3fcf40594af78f3694;
   unit balance = 100;
   string memory editedString;


   // Function logic


   return editedString //Returns "UserData: 0x8599fed66e2a440f12e9bc3fcf40594af78f3694, 100" 

}

The function should also work if the "format" is arranged differently. Example: "UserData: {balance}, {address}" ---> returns: "UserData: 100, 0x8599fed66e2a440f12e9bc3fcf40594af78f3694"

I did find some similar examples but I am not 100% sure how should I approach this.

find-word-in-string-solidity

solidity-how-to-replace-specific-string-position-with-letter

Any help would be appreciated.

2
  • See Nick Johnson's solidity-stringutils. Mar 1, 2022 at 9:53
  • @PaulRazvanBerg Thanks for the advice, but when I am trying to import the lib I get an error (ParserError: Source file requires a different compiler version). In short, the lib seems to be 3-4 years outdated (using 0.4.14). While I am using 0.8.9
    – Sky
    Mar 1, 2022 at 10:45

1 Answer 1

1

Solady's LibString has a replace method:

function replace(string memory subject, string memory search, string memory replacement)
    internal
    pure
    returns (string memory result)
{
    // --- snip --- //
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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