String
The String object is used to represent and manipulate a sequence of characters.
Description
Strings are useful for holding data that can be represented in text form. Some of the most-used operations on strings are to check their length , to build and concatenate them using the + and += string operators, checking for the existence or location of substrings with the indexOf() method, or extracting substrings with the substring() method.
Creating strings
Strings can be created as primitives, from string literals, or as objects, using the String() constructor:
const string1 = "A string primitive"; const string2 = 'Also a string primitive'; const string3 = `Yet another string primitive`;
const string4 = new String("A String object");
String primitives and string objects share many behaviors, but have other important differences and caveats. See «String primitives and String objects» below.
String literals can be specified using single or double quotes, which are treated identically, or using the backtick character ` . This last form specifies a template literal: with this form you can interpolate expressions. For more information on the syntax of string literals, see lexical grammar.
Character access
There are two ways to access an individual character in a string. The first is the charAt() method:
"cat".charAt(1); // gives value "a"
The other way is to treat the string as an array-like object, where individual characters correspond to a numerical index:
"cat"[1]; // gives value "a"
When using bracket notation for character access, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable. (See Object.defineProperty() for more information.)
Comparing strings
const a = "a"; const b = "b"; if (a b) // true console.log(`$a> is less than $b>`); > else if (a > b) console.log(`$a> is greater than $b>`); > else console.log(`$a> and $b> are equal.`); >
Note that all comparison operators, including === and == , compare strings case-sensitively. A common way to compare strings case-insensitively is to convert both to the same case (upper or lower) before comparing them.
function areEqualCaseInsensitive(str1, str2) return str1.toUpperCase() === str2.toUpperCase(); >
The choice of whether to transform by toUpperCase() or toLowerCase() is mostly arbitrary, and neither one is fully robust when extending beyond the Latin alphabet. For example, the German lowercase letter ß and ss are both transformed to SS by toUpperCase() , while the Turkish letter ı would be falsely reported as unequal to I by toLowerCase() unless specifically using toLocaleLowerCase(«tr») .
const areEqualInUpperCase = (str1, str2) => str1.toUpperCase() === str2.toUpperCase(); const areEqualInLowerCase = (str1, str2) => str1.toLowerCase() === str2.toLowerCase(); areEqualInUpperCase("ß", "ss"); // true; should be false areEqualInLowerCase("ı", "I"); // false; should be true
A locale-aware and robust solution for testing case-insensitive equality is to use the Intl.Collator API or the string’s localeCompare() method — they share the same interface — with the sensitivity option set to «accent» or «base» .
const areEqual = (str1, str2, locale = "en-US") => str1.localeCompare(str2, locale, sensitivity: "accent" >) === 0; areEqual("ß", "ss", "de"); // false areEqual("ı", "I", "tr"); // true
The localeCompare() method enables string comparison in a similar fashion as strcmp() — it allows sorting strings in a locale-aware manner.
String primitives and String objects
Note that JavaScript distinguishes between String objects and primitive string values. (The same is true of Boolean and Numbers .)
String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (that is, called without using the new keyword) are primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup on the wrapper object instead.
const strPrim = "foo"; // A literal is a string primitive const strPrim2 = String(1); // Coerced into the string primitive "1" const strPrim3 = String(true); // Coerced into the string primitive "true" const strObj = new String(strPrim); // String with new returns a string wrapper object. console.log(typeof strPrim); // "string" console.log(typeof strPrim2); // "string" console.log(typeof strPrim3); // "string" console.log(typeof strObj); // "object"
Warning: You should rarely find yourself using String as a constructor.
String primitives and String objects also give different results when using eval() . Primitives passed to eval are treated as source code; String objects are treated as all other objects are, by returning the object. For example:
const s1 = "2 + 2"; // creates a string primitive const s2 = new String("2 + 2"); // creates a String object console.log(eval(s1)); // returns the number 4 console.log(eval(s2)); // returns the string "2 + 2"
For these reasons, the code may break when it encounters String objects when it expects a primitive string instead, although generally, authors need not worry about the distinction.
A String object can always be converted to its primitive counterpart with the valueOf() method.
.log(eval(s2.valueOf())); // returns the number 4
String coercion
Many built-in operations that expect strings first coerce their arguments to strings (which is largely why String objects behave similarly to string primitives). The operation can be summarized as follows:
- Strings are returned as-is.
- undefined turns into «undefined» .
- null turns into «null» .
- true turns into «true» ; false turns into «false» .
- Numbers are converted with the same algorithm as toString(10) .
- BigInts are converted with the same algorithm as toString(10) .
- Symbols throw a TypeError .
- Objects are first converted to a primitive by calling its [@@toPrimitive]() (with «string» as hint), toString() , and valueOf() methods, in that order. The resulting primitive is then converted to a string.
There are several ways to achieve nearly the same effect in JavaScript.
- Template literal: `$` does exactly the string coercion steps explained above for the embedded expression.
- The String() function: String(x) uses the same algorithm to convert x , except that Symbols don’t throw a TypeError , but return «Symbol(description)» , where description is the description of the Symbol.
- Using the + operator: «» + x coerces its operand to a primitive instead of a string, and, for some objects, has entirely different behaviors from normal string coercion. See its reference page for more details.
Depending on your use case, you may want to use `$` (to mimic built-in behavior) or String(x) (to handle symbol values without throwing an error), but you should not use «» + x .
UTF-16 characters, Unicode code points, and grapheme clusters
Strings are represented fundamentally as sequences of UTF-16 code units. In UTF-16 encoding, every code unit is exact 16 bits long. This means there are a maximum of 2 16 , or 65536 possible characters representable as single UTF-16 code units. This character set is called the basic multilingual plane (BMP), and includes the most common characters like the Latin, Greek, Cyrillic alphabets, as well as many East Asian characters. Each code unit can be written in a string with \u followed by exactly four hex digits.
However, the entire Unicode character set is much, much bigger than 65536. The extra characters are stored in UTF-16 as surrogate pairs, which are pairs of 16-bit code units that represent a single character. To avoid ambiguity, the two parts of the pair must be between 0xD800 and 0xDFFF , and these code units are not used to encode single-code-unit characters. (More precisely, leading surrogates, also called high-surrogate code units, have values between 0xD800 and 0xDBFF , inclusive, while trailing surrogates, also called low-surrogate code units, have values between 0xDC00 and 0xDFFF , inclusive.) Each Unicode character, comprised of one or two UTF-16 code units, is also called a Unicode code point. Each Unicode code point can be written in a string with \u where xxxxxx represents 1–6 hex digits.
A «lone surrogate» is a 16-bit code unit satisfying one of the descriptions below:
- It is in the range 0xD800 – 0xDBFF , inclusive (i.e. is a leading surrogate), but it is the last code unit in the string, or the next code unit is not a trailing surrogate.
- It is in the range 0xDC00 – 0xDFFF , inclusive (i.e. is a trailing surrogate), but it is the first code unit in the string, or the previous code unit is not a leading surrogate.
Lone surrogates do not represent any Unicode character. Although most JavaScript built-in methods handle them correctly because they all work based on UTF-16 code units, lone surrogates are often not valid values when interacting with other systems — for example, encodeURI() will throw a URIError for lone surrogates, because URI encoding uses UTF-8 encoding, which does not have any encoding for lone surrogates. Strings not containing any lone surrogates are called well-formed strings, and are safe to be used with functions that do not deal with UTF-16 (such as encodeURI() or TextEncoder ). You can check if a string is well-formed with the isWellFormed() method, or sanitize lone surrogates with the toWellFormed() method.
On top of Unicode characters, there are certain sequences of Unicode characters that should be treated as one visual unit, known as a grapheme cluster. The most common case is emojis: many emojis that have a range of variations are actually formed by multiple emojis, usually joined by the ( U+200D ) character.
You must be careful which level of characters you are iterating on. For example, split(«») will split by UTF-16 code units and will separate surrogate pairs. String indexes also refer to the index of each UTF-16 code unit. On the other hand, @@iterator() iterates by Unicode code points. Iterating through grapheme clusters will require some custom code.
"".split(""); // ['\ud83d', '\ude04']; splits into two lone surrogates // "Backhand Index Pointing Right: Dark Skin Tone" [. ""]; // ['', ''] // splits into the basic "Backhand Index Pointing Right" emoji and // the "Dark skin tone" emoji // "Family: Man, Boy" [. ""]; // [ '', '', '' ] // splits into the "Man" and "Boy" emoji, joined by a ZWJ // The United Nations flag [. ""]; // [ '', '' ] // splits into two "region indicator" letters "U" and "N". // All flag emojis are formed by joining two region indicator letters
Constructor
Creates a new String object. It performs type conversion when called as a function, rather than as a constructor, which is usually more useful.
Static methods
Returns a string created by using the specified sequence of Unicode values.
Returns a string created by using the specified sequence of code points.
Returns a string created from a raw template string.
Instance properties
These properties are defined on String.prototype and shared by all String instances.
The constructor function that created the instance object. For String instances, the initial value is the String constructor.
These properties are own properties of each String instance.
Reflects the length of the string. Read-only.
Instance methods
Returns the character (exactly one UTF-16 code unit) at the specified index . Accepts negative integers, which count back from the last string character.
Returns the character (exactly one UTF-16 code unit) at the specified index .
Returns a number that is the UTF-16 code unit value at the given index .
Returns a nonnegative integer Number that is the code point value of the UTF-16 encoded code point starting at the specified pos .
Combines the text of two (or more) strings and returns a new string.
Determines whether a string ends with the characters of the string searchString .
Determines whether the calling string contains searchString .
Returns the index within the calling String object of the first occurrence of searchValue , or -1 if not found.
Returns a boolean indicating whether this string contains any lone surrogates.
Returns the index within the calling String object of the last occurrence of searchValue , or -1 if not found.
Returns a number indicating whether the reference string compareString comes before, after, or is equivalent to the given string in sort order.
Used to match regular expression regexp against a string.
Returns an iterator of all regexp ‘s matches.
Returns the Unicode Normalization Form of the calling string value.
Pads the current string from the end with a given string and returns a new string of the length targetLength .
Pads the current string from the start with a given string and returns a new string of the length targetLength .
Returns a string consisting of the elements of the object repeated count times.
Used to replace occurrences of searchFor using replaceWith . searchFor may be a string or Regular Expression, and replaceWith may be a string or function.
Used to replace all occurrences of searchFor using replaceWith . searchFor may be a string or Regular Expression, and replaceWith may be a string or function.
Search for a match between a regular expression regexp and the calling string.
Extracts a section of a string and returns a new string.
Returns an array of strings populated by splitting the calling string at occurrences of the substring sep .
Determines whether the calling string begins with the characters of string searchString .
Returns a portion of the string, starting at the specified index and extending for a given number of characters afterwards.
Returns a new string containing characters of the calling string from (or between) the specified index (or indices).
The characters within a string are converted to lowercase while respecting the current locale.
For most languages, this will return the same as toLowerCase() .
The characters within a string are converted to uppercase while respecting the current locale.
For most languages, this will return the same as toUpperCase() .
Returns the calling string value converted to lowercase.
Returns a string representing the specified object. Overrides the Object.prototype.toString() method.
Returns the calling string value converted to uppercase.
Returns a string where all lone surrogates of this string are replaced with the Unicode replacement character U+FFFD.
Trims whitespace from the beginning and end of the string.
Trims whitespace from the end of the string.
Trims whitespace from the beginning of the string.
Returns the primitive value of the specified object. Overrides the Object.prototype.valueOf() method.
Returns a new iterator object that iterates over the code points of a String value, returning each code point as a String value.
HTML wrapper methods
Warning: Deprecated. Avoid these methods.
They are of limited use, as they are based on a very old HTML standard and provide only a subset of the currently available HTML tags and attributes. Many of them create deprecated or non-standard markup today. In addition, they do simple string concatenation without any validation or sanitation, which makes them a potential security threat when directly inserted using innerHTML . Use DOM APIs such as document.createElement() instead.
String.prototype.anchor() Deprecated
Note that these methods do not check if the string itself contains HTML tags, so it’s possible to create invalid HTML:
"".bold(); //
The only escaping they do is to replace » in the attribute value (for anchor() , fontcolor() , fontsize() , and link() ) with " .
Examples
String conversion
The String() function is a more reliable way of converting values to strings than calling the toString() method of the value, as the former works when used on null and undefined . For example:
// You cannot access properties on null or undefined const nullVar = null; nullVar.toString(); // TypeError: Cannot read properties of null String(nullVar); // "null" const undefinedVar = undefined; undefinedVar.toString(); // TypeError: Cannot read properties of undefined String(undefinedVar); // "undefined"
Specifications
| Specification |
|---|
| ECMAScript Language Specification # sec-string-objects |
Browser compatibility
BCD tables only load in the browser
See also
- Text formatting guide
- RegExp
Found a content problem with this page?
- Edit the page on GitHub.
- Report the content issue.
- View the source on GitHub.
This page was last modified on Sep 26, 2023 by MDN contributors.
Your blueprint for a better internet.
String
String — тип данных в Solidity, который представляет строковые значения. Он используется для хранения и обработки текстовых данных, таких как имена, адреса, текстовые сообщения и т.д. Строковые значения могут содержать любое количество символов и могут быть произвольной длины.
В Solidity строковые значения представляются в формате UTF-8. Они могут содержать символы на любом языке. Однако в Solidity каждый символ занимает определенное количество байт, поэтому необходимо учитывать размер строковых значений при их обработке.
string penis = "Hello World!";
На данном этапе Solidity имеет некоторые ограничения по работе с строчными переменными. В языке нет возможности конкатенировать строки, обрезать их, и указывать на конкретный элемент строки.
С другой стороны строки в Solidity это далеко не самый важный тип данных и на стороне смарт-контракта нам не особо нужно играться со строками, поэтому разработчики могли намеренно убрать эти возможности, чтобы излишне не нагружать EVM бесполезными действиями.
Примеры кода с использованием string
Строковые значения в Solidity могут использоваться для передачи параметров в функции и для хранения данных в памяти. Для обработки строковых значений в Solidity можно использовать различные функции и операторы.
Например в этом коде мы объявляем переменную text с трипом данных string. После чего создаем функцию, которая принимает в качестве аргумента переменную message и задает ее в качестве значение переменной text.
pragma solidity ^0.8.0; contract LearnStrings < string public text; function setTextByPassing(string memory message) public < text = message; >>
По сути мы получаем элементарный код, одна часть которого задает данные, а вторая часть которого их хранит.
Типы данных
Строка. Тип данных string. Строковые переменные, их описание. Длина строки. Операции над строками
Строка (string) — это последовательность литер. Литерные строки уже использовались нами в качестве аргументов операторa write при изучении темы «Ввод-вывод». Теперь познакомимся с ними подробнее.
Тип данных (string) определяет строки с максимальной длиной 255 символов. Переменная этого типа может принимать значения переменной длины.
| MaxLine : string; City : string[30] |
Строковая переменная может иметь атрибут длины, определяющий ее максимальную длину.
Текущая длина строковой переменной может быть определена с помощью встроенной функции Length. Для заданного значения типа string эта функция возвращает целое значение, показывающее количество литер в строке.
Выражения, в которых операндами служат строки, называются строковыми выражениями.
Над строками определены следующие операции:
1. Операция конкатенации (+) применяется для сцепления нескольких строк в одну.
Например,
SumStr := ‘Турбо ‘+’Паскаль ‘+’7.0’
Если строки имеют различную длину, но в их общей части символы совпадают, считается, что более короткая строка меньше, чем более длинная.
Строки считаются равными, если они совпадают по длине и содержат одни и те же символы на соответствующих местах в строке.
Для присваивания строковой переменной результата строкового выражения используется оператор присваивания. Если значение переменной после выполнения оператора присваивания превышает по длине максимально допустимую при описании величину, то все лишние символы справа отбрасываются.
Допускается смешение в одном выражении операндов строкового и символьного типа.
К отдельным символам строки можно обратиться по номеру (индексу) данного символа в строке.
Например, чтобы обратиться к третьему символу строки SumStr надо записать SumStr[3]. Запись SumStr[0] дает значение текущей длины строки.
Для эффективного программирования алгоритмов обработки текстов необходимо хорошо понимать внутреннюю структуру представления строк в памяти. Строки реализованы достаточно просто. Для хранения строковых переменных выделяется количество байтов памяти, на единицу большее максимальной длины строки. Начальный байт этой памяти отводится для хранения текущей длины строки, следующие байты — для символов самой строки. Так как элементы строк стандартно нумеруются целыми числами, начиная с единицы, байт с длиной строки можно считать нулевым ее элементом. Такая структура памяти допускает прямой доступ к ее элементам.
Важно отметить, что имеется возможность динамически управлять текущей длиной строки. Следующая программа показывает автоматическое изменение длины строки после тех или иных операций с нею. Обратите внимание, что общий (определяемый с помощью стандартной функции SizeOf) размер памяти, отведенной для хранения строки все время остается неизменным.
| Program StringLength; Var S : string; Begin S:=»; writeln (S,’ ‘,SizeOf(S),’ ‘,Length(S)); S:=’Пример длинной строки’; writeln (S,’ ‘,SizeOf(S),’ ‘,Length(S)); Delete(S,7,8); writeln (S,’ ‘,SizeOf(S),’ ‘,Length(S)); S:=S+’ символов’; writeln (S,’ ‘,SizeOf(S),’ ‘,Length(S)); End. |
Внимание! При решении задач со строковыми переменными Вы можете столкнуться с распространенной трудно обнаруживаемой ошибкой, когда после присваивания некоторым элементам строки символов ни содержимое, ни длина строки не изменяются. Разберемся, с чем это связано.
Очень важно понимать, что при доступе к некоторому элементу строки значение ее текущей длины не проверяется. Это иллюстрирует следующая программа:
| Program StringElements; Var S : string; Begin S:=’ABCD’; writeln (S,’ ‘,Length(S)); S[5] := ‘E’; writeln (S,’ ‘,Length(S)); End. |
Присваивание пятому элементу строки некоторого значения не изменяет длину строки, что подтверждает вывод на экран ее содержимого и длины (конечно само присваивание реально произошло, но на значение текущей длины строки в нулевом байте это никакого влияния не оказало). Работа с элементами строки без учета ее текущей длины и является ошибкой программиста. Посмотрите следующую программу:
| Program StringElements2; Var Str : string[26]; i : integer; Begin Str:=’A’; for i := 1 to 26 do Str[i] := Chr (Ord(‘A’)+i-1); writeln(Str); End. |
Предполагается, что данная программа должна сформировать строку из 26 символов, содержимым которой является последовательность заглавных букв латинского алфавита. Однако вызов процедуры writeln показывает, что содержимым переменной Str будет строка из одного символа ‘А’. Природа совершенной ошибки заключается в том, что присваивание значений элементам строки не влияет на текущую длину, которая была установлена равной 1 при первом присваивании. Поэтому правильной будет следующая программа:
| Program stringElements3; Var Str : string[26]; i : char; Begin Str:=»; for i := ‘A’ to ‘Z’ do Str := Str + i; writeln(Str); End. |
Операция конкатенации, как и все стандартные операции, работающие со строками, в отличие от поэлементного присваивания, изменяет длину строки, что дает корректный результат. Кроме того, вторая программа работает непосредственно с символами букв. Наконец, не следует забывать инициализировать строку перед ее заполнением (первый оператор программы). В противном случае, так как начальная длина строки является неопределенной, можно получить произвольный результат; не стоит рассчитывать на то, что в нулевом байте стоит ноль.
Для обработки строковых данных можно использовать встроенные процедуры и функции:
-
Delete (Str, Poz, N) — удаление N символов строки Str, начиная с позиции Poz.
Строковый тип данных в Python: string
Строка — это некоторая последовательность символов. В языке Python строковые данные имеют формат str.
Строка в Python
Создадим первую текстовую переменную. Для создания строки можно использовать как одинарные, так и двойные кавычки:
>>> s = 'Hello world' >>> s 'Hello world' >>> s = "Hello world" >>> s 'Hello world'
Вывод в Python всегда будет в одинарных кавычках, так как производится перевод двойных кавычек в одинарные.
Проверим тип этой переменной:
>>> type(s)
Если необходимо задать большой фрагмент текста, то используются тройные кавычки:
>>> s='''Hello World!!''' >>> s 'Hello\nWorld!!'
В данном примере сохранился знак перехода на новую строку (‘\n’).
Преобразование чисел в строки и обратно
Любое число можно преобразовать в строку. Для этого используется функция str() давайте попробуем:
>>> str(1232) '1232' >>> str(-0.5) '-0.5'
Теперь попробуем выполнить обратное действие
>>> s = '123' >>> int(s) 123 >>> float(s) 123.0 >>> s = '1.23' >>> float(s) 1.23 >>> int(s) Traceback (most recent call last): File "", line 1, in int(s) ValueError: invalid literal for int() with base 10: '1.23'
Если вид числа не удовлетворяет типу данных, то преобразование не выполняется. Компилятор выдает ошибку вида invalid literal, что в переводе означает недопустимый литерал (символ), из-за наличия точки, то есть данное число является числом с плавающей точкой (float).
Чтобы избежать данной ошибки, в первую очередь необходимо выполнить преобразование в тип float. Если нужно, то затем преобразовываем полученный float в int.
>>> s='0.23' >>> int(float(s)) 0
Основные операции со строками в Python
Длина строки
В Python строка представляет собой массив символов, расположенных в определенной последовательности. Когда мы пишем:
>>> s='Hello world'
Компьютер представляет это следующим образом:
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| H | e | l | l | o | w | o | r | l | d |
Воспользуемся функцией len(), чтобы узнать длину строки.
>>> len(s) 11
Как и было указано выше, длина данной строки — 11 символов (нумерация начинается с нуля).
Строка является массивом, поэтому мы можем обратиться к каждому отдельному элементу строки, давайте попробуем:
>>> s[2] 'l' >>> s[4] 'o'
Также можно получить, так называемый срез слова, то есть фрагмент из общей последовательности символов. Для этого нужно указать диапазон:
>>> s='Hello world' >>> s[2:5] 'llo'
Сложение строк
Давайте попробуем сложить 2 строки:
>>> s1='Hello' >>> s2='world' >>> s1+s2 'Helloworld'
Также при сложении можно добавлять не только переменные, которым присвоены строки, но и просто сами строки:
>>> s1='Hello' >>> s2='world' >>> s1+' '+s2+"!" 'Hello world!'
Попробуем сложить строки и числа:
>>> s1='number ' >>> s1+1 Traceback (most recent call last): File "", line 1, in s1+1 TypeError: can only concatenate str (not "int") to str
Строковой тип данных можно складывать только с таким же типом.
Достаточно выполнить преобразование, чтобы получить правильное решение:
>>> s1+str(1) 'number 1'
Умножение строк
Давайте попробуем выполнить различные умножения: на целое число, на дробное число, на само себя:
>>> s='Hi' >>> s*2 'HiHi' >>> s*1.2 Traceback (most recent call last): File "", line 1, in s*1.2 TypeError: can't multiply sequence by non-int of type 'float' >>> s*s Traceback (most recent call last): File "", line 1, in s*s TypeError: can't multiply sequence by non-int of type 'str'
Операция умножения в данном случае является дублированием строки. Такое действие можно выполнить только целое число раз, поэтому при умножении на дробное число или на строку выдаёт ошибку.
Умножать строковой тип данных можно только на целые числа.
Курсы Робикс, в которых изучается этот материал.
- Программирование на Python в Minecraft
- Duckietown робот с системой Автопилота
