- 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.
- 普林斯頓微積分讀本(修訂版)
- 西去東來:沿絲綢之路數(shù)學(xué)知識的傳播與交流
- 感官的盛宴:數(shù)學(xué)之眼看藝術(shù)(萬物皆數(shù)學(xué))
- Introduction to Blockchain and Ethereum
- 小數(shù)學(xué)家應(yīng)該知道的數(shù)學(xué)故事
- 高等數(shù)學(xué)習(xí)題全解(下冊)
- 數(shù)學(xué)建模33講:數(shù)學(xué)與繽紛的世界
- Mastering Ethereum
- 2頁紙圖解數(shù)學(xué):以極聰明的方式,讓你三步讀懂數(shù)學(xué)
- 證明與布丁
- 代數(shù)的歷史:人類對未知量的不舍追蹤(修訂版)
- 圖解數(shù)學(xué)思維訓(xùn)練課:建立孩子的數(shù)學(xué)模型思維(多步計算應(yīng)用訓(xùn)練課)
- 線性代數(shù)同步精講及練習(xí)
- 自然哲學(xué)的數(shù)學(xué)原理(漢譯世界學(xué)術(shù)名著叢書)
- 數(shù)學(xué)家、間諜與黑客:密碼與解碼(萬物皆數(shù)學(xué))