1

I have specific Requirements for a project, where i have to store multiple strings against one owner in a mapping but i noticed there is no string arrays in solidity

Is there an alternative way of doing it?

1

1 Answer 1

2

You can definitely achieve that using mappings to dynamic arrays. You can map an address or any other identifier to a dynamic array of strings, by defining a mapping variable like:

mapping(address => string[]) stringMap;

Here’s an example contract for the same:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract StringStorage {
    mapping(address => string[]) stringMap;

    function addString(address owner, string memory newString) public {
        stringMap[owner].push(newString);
    }

    function getStrings(address owner) public view returns (string[] memory) {
        return stringMap[owner];
    }
}

This basic contract allows you to store multiple strings for each address and retrieve them as needed.

So, if you call the addString()function by passing the corresponding arguments of type address and string as:

  1. 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4, hello

    enter image description here

  2. 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4, world

    enter image description here

Now, when you call the getStrings() function by passing the corresponding address argument as 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4, then it'll return an array of 2 strings as:

string[]: hello,world

enter image description here

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.