官术网_书友最值得收藏!

  • Mastering Ethereum
  • Merunas Grincalaitis
  • 257字
  • 2021-06-24 15:01:04

Strings and bytes

Strings and bytes hold pieces of text in single or double quotes, as follows:

string public myText = “This is a long text”;
bytes public myTextTwo = “This is another text”;

They allow you to store about 1,000 words and they are essentially the same. You can have smaller variations of bytes, such as bytes1, bytes2, and bytes3, up to bytes32.

Now, bytes32 is an interesting type of variable, because it allows you to store about 32 characters of text in a very compact and efficient way. They are used in many cases where short text is required:

bytes32 public shortText = “Short text.”;

They are used in many other advanced uses cases, such as checking if a string or byte's text is empty. For instance, if you have a function that receives text, you may want to make sure that the text is not empty. Here's how you'd do it:

function example(string memory myText) public {
require(bytes(myText)[0] != 0);
}

Don't worry about the technicalities of the function. If you don't know or remember them yet, to check if a string is empty, you must do the following:

require(bytes(yourString)[0] != 0);

This tells the contract to make sure that the first letter of the string is not empty. That's the right way to check for empty strings. We do the same thing with bytes, but without the conversion to bytes.

Use them whenever you need to add special characters to your strings in Ethereum.

主站蜘蛛池模板: 焦作市| 天等县| 虹口区| 青川县| 贺州市| 临清市| 凌海市| 银川市| 石首市| 庄浪县| 贵港市| 榆社县| 习水县| 东宁县| 五寨县| 泰来县| 堆龙德庆县| 循化| 临夏县| 铜陵市| 淅川县| 大新县| 腾冲县| 库伦旗| 梁平县| 镇安县| 探索| 宜城市| 大方县| 乌兰县| 呼和浩特市| 井冈山市| 中江县| 汉源县| 竹溪县| 乌审旗| 留坝县| 玛曲县| 汕尾市| 镇巴县| 泌阳县|