Menu
Is free
registration
home  /  Multimedia/ Functions for working with line 1s. New functions for working with strings

Functions for working with line 1c. New functions for working with strings

Hello everyone
Today they asked me not to display the prefix of the document when printing the implementation document, the problem was solved as follows.

StrReplace (Number, Leo (Number, 3), "");

When I looked into the syntax assistant, I liked it so much that I wanted to write about working with strings in 1C: Enterprise.

A string in 1C refers to a primitive data type.

If you look at the 1C help, we will see the following description of the String type
Values ​​of this type contain an arbitrary length Unicode string.
If in your own words about strings it will work out. A string is a constant, consisting of various characters, always surrounded by quotes.

Specifying a string
Call = "Hello Passenger";

Multi-line strings in typical configurations are most often created using the vertical "|" separator:
String = "Multiline
| string
| write
| text ";

The quotation mark inside the string is specified by double quotation marks.
String = "" Text in quotation marks "";

There are many operations on strings (search in the inside of a string, determining the first, etc.), it is better to look at the Syntax Assistant.
Syntax Assistant - General description of the built-in language-> built-in functions-> functions for working with strings.

String functions

Here, in a short form, I will give the functions for working with strings:

BReg (<Строка>) - The function converts all characters in the string to uppercase.

SymbolCode (<Строка>, <НомерСимвола>) - The function receives the code of the character located in the passed string at the position with the specified number.

A lion(<Строка>, <ЧислоСимволов>) - The function selects the first characters from the left of the string.

Find(<Строка>, <ПодстрокаПоиска>) - The function finds the occurrence of the search string as a substring in the original string.

HPreg (<Строка>) - The function converts all characters in the string to lowercase.

Right (<Строка>, <ЧислоСимволов>) - This function differs from the Left functions in that it selects the last characters of the string on the right.

Empty line(<Строка>) - The function checks the string for significant characters.

Symbol(<КодСимвола>) - The function converts the character code to a string containing the character.

AbbrL (<Строка>) - The function cuts off insignificant characters to the left of the first significant character in the string.

SocrLP (<Строка>) - The function strips off insignificant characters to the left of the first significant character in the line, and spaces to the right of the last significant character in the line.

Abbreviation (<Строка>) - The function cuts off insignificant characters to the right of the last significant character in the string.

Wednesday (<Строка>, <НачальныйНомер>, <ЧислоСимволов>) - The function selects a character string starting with a character<НачальныйНомер>, in total<ЧислоСимволов>.

StrLength (<Строка>) - The function gets the number of characters in a string.

PReplace (<Строка>, <ПодстрокаПоиска>, <ПодстрокаЗамены>) - The function finds all occurrences of the search substring in the original string and replaces it with the replacement substring.

StrGetString (<Строка>, <НомерСтроки>) - The function gets a string of a multi-line string by number.

StrNumber of Occurrences (<Строка>, <ПодстрокаПоиска>) - The function calculates the number of occurrences of the search substring in the original string.

StrNumber of Lines (<Строка>) - The function counts the number of lines in a multi-line string. In a multi-line string, the lines are separated by linefeed characters.

Treg (<Строка>) - The function converts the string to the title case. This means that for each word, the first character is converted to a title case, or to upper case if no title case is defined for the character. The rest of the characters are converted to lowercase.

Type conversions
For explicit conversion of data types, there are functions of the same name with the data type to which the conversion occurs: String (<Значение>)

StringOfNumbers = String (Number);

All these functions are described in detail in the Syntax Assistant, how the Syntax Assistant can help a beginner programmer, I described in the article.

Examples for working with strings

Convert a number to a string and back.

To get a string representation of the year, use the Format function.

Year = Format (CurrentDate (), "DF = yyyy") // Year = "2012"

To convert a number to a string without inserting a group separator character (non-breaking space), you must use the Format function with the ChG = 0 parameter:

Number = 2012 String = Format (Number, "CHG = 0"); // String = "2012"

String No spaces.

Notes from the Looking Glass

08/18/2014 New functions for working with strings

Implemented in version 8.3.6.1977.

We have expanded the set of functions for working with strings. We did this in order to give you more advanced tools for parsing string data. The new functions will be convenient and useful in technological tasks of text analysis. In tasks related to parsing text that contains formatted data. This can be the analysis of some files received from the equipment, or, for example, the analysis of a technological log.

All actions that perform new functions, you could have performed before. With the help of more or less complex algorithms written in an embedded language. Therefore, the new functions do not give you any fundamentally new possibilities. However, they can reduce the amount of code, make the code simpler and easier to understand. And besides that, they allow you to speed up the execution of actions. Because the functions implemented in the platform work, of course, faster than a similar algorithm written in an embedded language.

Formatting function StrPattern ()

This function substitutes parameters into a string. The need for such a conversion often arises, for example, when displaying warning messages. The syntax for this function is as follows:

StrPattern (<Шаблон>, <Значение1-Значение10>)

<Шаблон>is a string to substitute for parameter representations.

<Значение1> , ... <Значение10>- these are parameters (maximum - ten), the representations of which must be substituted into the string.

To indicate a specific place in the template where you want to perform substitution, you need to use tokens of the form% 1, ...% 10. The number of markers used in the template and the number of parameters containing values ​​must be the same.

For example, the result of executing such a statement:

there will be a line:

Data error on line 2 (Date type required)

Function for working with strings StrCompare ()

This function compares two strings in a case insensitive manner. For example, like this:

You could have performed the same action before using the object Comparison of Values:

However, using the new function looks simpler. And besides this, a function, unlike an object Comparison of Values, works in both the thin client and the web client.

Functions for working with strings RowStart With (), RREnd With ()

These functions determine whether a string begins with a specified substring or ends with a specified substring. The algorithm of these functions is not difficult to implement in the embedded language, but their presence allows you to write cleaner and more understandable code. And they work faster.

For example, it is convenient to use them in the operator If:

Functions for working with strings StrSplit (), StrConnect ()

These functions split the string into parts according to the specified delimiter. Or vice versa, they combine several lines into one, inserting the selected separator between them. They are convenient for creating or analyzing logs, technological logs. For example, you can easily disassemble a record of a technological log into parts suitable for further analysis:

Function for working with strings StrFind ()

Instead of the old function Find() we have implemented a new feature that has additional capabilities:

  • Search in different directions (from the beginning, from the end);
  • Search from a specified position;
  • Search for an occurrence with the specified number (second, third, etc.).

In fact, it duplicates the capabilities of the old function. This is done in order to maintain compatibility with modules compiled in older versions. Old function Find() it is recommended not to use it again.

Below is an example using the new search capabilities. Backward searches are useful when you need the last piece of a formalized string, such as the fully qualified filename in a URL. And searching from a specified position helps in cases when you need to search in a known fragment, and not in the entire string.

There are few mechanisms for working with strings in 1C queries. First, the lines can be added. Secondly, you can take a substring from a string. Third, strings can be compared, including by pattern. That's probably all you can do with strings.

Concatenation of strings

To add strings in a query, the "+" operation is used. Only lines of limited length can be folded.

SELECT "Name:" + Counterparties. Name AS Column1 FROM Directory. Counterparties AS Counterparties WHERE Counterparties. Link = & Link

Substring function

SUBSTRATE (<Строка>, <НачальнаяПозиция>, <Длина>)

Analogue of the function Environment () from the object model. The Substring () function can be applied to data of a string type and allows you to select a fragment <Строки> starting with the character number <НачальнаяПозиция> (characters in the string are numbered from 1) and length <Длина> characters. The result of evaluating the function has a variable-length string type, and the length will be considered unlimited if <Строка> has unlimited length and parameter <Длина> is not constant or exceeds 1024.

If the length of the string is less than that specified in the second parameter, then the function will return an empty string.

Attention! Using the SUBSTRING () function to convert strings of unlimited length to strings of limited length is not recommended. It is better to use a cast operation like EXPRESS () instead.

Function Like

If we need to make sure that a string attribute meets certain criteria, we compare it:

SELECT Counterparties. Name AS Column1 FROM Directory. Counterparties AS Counterparties WHERE Counterparties. Name = "Gazprom"

But what if you want a trickier comparison? Not just equality or inequality, but like a certain pattern? This is exactly what the function LIKE is created for.

LIKE - Operator for checking a string like a pattern. Analogue of LIKE in SQL.

The LIKE operator allows you to compare the value of the expression specified to the left of it with the template string specified to the right. The expression value must be of type string. If the expression value matches the pattern, the operator will result in TRUE, otherwise - FALSE.

The following characters in the template string are service characters and have a meaning other than the string character:

  • % (percentage): a sequence containing any number of arbitrary characters;
  • _ (underscore): one arbitrary character;
  • […] (One or more characters in square brackets): any single character listed within square brackets. The enumeration may contain ranges, for example, a-z, meaning an arbitrary character included in the range, including the ends of the range;
  • [^…] (In square brackets a negation sign followed by one or more characters): any single character other than those listed after the negation sign.

Any other symbol means itself and does not carry any additional meaning. If it is necessary to write one of the listed characters as oneself, then it must be preceded by<Спецсимвол>... Myself<Спецсимвол>(any suitable character) is defined in the same statement after the SPECIAL CHARACTER keyword.

Strings in 1C 8.3 in the built-in language 1c represent values ​​of a primitive type Line... Values ​​of this type contain an arbitrary length Unicode string. Variables of string type are a set of characters enclosed in quotation marks.

Example 1. Let's create a string variable with text.

StringVariable = "Hello world!";

Functions for working with strings in 1c 8.3

In this section, the main functions will be given that allow you to change the lines in 1c, or analyze the information contained in them.

Str Length

StrLength (<Строка>) ... Returns the number of characters contained in the string passed in the parameter.

Example 2. Let's count the number of characters in the string "Hello world!"

String = "Hello world!"; Number of Characters = StrLength (String); Report (Number of Characters);

The result of executing this code will be the display of the number of characters in the string: 11.

Abbreviation

AbbrL (<Строка>) ... Truncates insignificant characters to the left of the first significant character in the string.
Minor characters:

  • space;
  • non-breaking space;
  • tabulation;
  • carriage return;
  • line translation;
  • translation of the form (page).

Example 3. Remove all spaces from the left side of the line "world!" and attach the string "Hello" to it.

String = abbreviated ("peace!"); String = "Hello" + String; Report (String);

The result of the execution of this code will be the output of the line "Hello world!"

Abbreviation

Abbreviation (<Строка>) ... Truncates insignificant characters to the right of the first significant character in the string.

Example 4. Form "Hello" and "World!" the phrase "Hello world!"

String = abbreviated ("Hello") + "" + abbreviated ("world!"); Report (String);

SokrLP

SocrLP (<Строка>) ... Truncates insignificant characters to the right of the first significant character in a string, and also cuts insignificant characters to the left of the first significant character in a string. This function is used more often than the previous two, since it is more versatile.

Example 5. Remove insignificant characters on the left and right in the name of the counterparty.

Counterparty = Directories.Contractors.NaytiPoRequisite ("INN", "0777121211"); CounterpartyObject = Counterparty.GetObject (); CounterpartyObject.Name = SokrLP (CounterpartyObject.Name); CounterpartyObject.Write ();

a lion

A lion(<Строка>, <ЧислоСимволов>) ... Receives the first characters of a string, the number of characters is specified in the parameter Number of Characters.

Example 6. Let in the structure Employee contain the name, surname and patronymic of the employee. Get a string with the last name and initials.

InitialName = Leo (Employee.Name, 1); Patronymic Initial = Leo (Employee, Patronymic, 1); FullName = Employee.LastName + "" + InitialName + "." + Initial of Patronymic + ".";

Right

Right (<Строка>, <ЧислоСимволов>) ... Gets the last characters of a string, the number of characters is specified in the parameter Number of Characters. If the specified number of characters exceeds the length of the string, then the entire string is returned.

Example 7. Suppose that the end of a string variable contains a date in the format "yyyymmdd", get a string with a date and convert it to the type date.

String = "Current date: 20170910"; StringDate = Right (String, 8); Date = Date (StringDate);

Wednesday

Wednesday (<Строка>, <НачальныйНомер>, <ЧислоСимволов>) ... Gets a substring from a string passed as a parameter Line, starting from the character whose number is specified in the parameter StartNumber and the length passed to the parameter Number of Characters. The numbering of characters in the line starts from 1. If in the parameter StartNumber a value is specified that is less than or equal to zero, then the parameter takes on the value 1. If the parameter Number of Symbols is not specified, then characters up to the end of the line are selected.

Example 8. Suppose that the string variable starting from the ninth position contains the region code, you should get it and write it in a separate line.

Line = "Region: 99 Moscow"; Region = Wed (Line, 9, 2);

Search

Find (<Строка>, <ПодстрокаПоиска>, <НаправлениеПоиска>, <НачальнаяПозиция>, <НомерВхождения>) ... Searches for the specified substring in a string, returns the position number of the first character of the found substring. Consider the parameters of this function:

  • Line... Source string;
  • Substring... The substring to be searched for;
  • Search direction... Specifies the direction to search for a substring in a string. Can take values:
    • Search Direction. From Start;
    • Search Direction.;
  • Initial Position... Specifies the position in the string from which the search begins;
  • Number of Entries... Specifies the number of occurrences of the desired substring in the original string.

Example 9. In the line "Hello world!" determine the position of the last occurrence of the symbol "and".

PositionNumber = StrNayti ("Hello world!", "And", DirectionSearch.End); Report (Position Number);

The result of executing this code will be the display of the number of the last occurrence of the symbol "and": 9.

VReg

BReg (<Строка>) ... Converts all characters in the specified string in 1s 8 to uppercase.

Example 10. Convert the string "hello world!" to uppercase.

StringBreg = BReg ("hello world!"); Report (StringVreg);

The result of executing this code will be the display of the line "HELLO WORLD!"

Nreg

HPreg (<Строка>) ... Converts all characters of the specified string in 1s 8 to lowercase.

Example 11. Convert the string "HELLO WORLD!" to lower case.

StringNreg = НReg ("HELLO WORLD!"); Report (StringVreg);

The result of the execution of this code will be the output of the line "hello world!"

Treg

Treg (<Строка>) ... Converts a string as follows: the first character of each word is converted to uppercase, the remaining characters of the word are converted to lowercase.

Example 12. Capitalize the first letters of the words in the string "hello world!"

StringTreg = Treg ("hello world!"); Report (StringTreg);

The result of the execution of this code will be the output on the screen of the line "Hello World!"

Symbol

Symbol(<КодСимвола>) ... Gets a character by its Unicod code.

Example 13. Let's add to the left and right in the line "Hello World!" symbol ★

StringWithStars = Symbol ("9733") + "Hello World!" + Symbol ("9733"); Report (StringWithStars);

The result of executing this code will be the display of the line "★ Hello World! ★"

Symbol Code

SymbolCode (<Строка>, <НомерСимвола>) ... Gets the Unicode character code from the string specified in the first parameter, located at the position specified in the second parameter.

Example 14. Find out the code of the last character in the "Hello World!"

String = "Hello World!"; CharacterCode = CharacterCode (String, StrLength (String)); Report (SymbolCode);

The result of the execution of this code will be the display of the symbol code "!" - 33.

Empty line

Empty line(<Строка>) ... Checks if a string contains only insignificant characters, that is, if it is empty.

Example 15. Check if a string consisting of three spaces is empty.

Empty = EmptyString (""); Report (Empty);

The result of the execution of this code will be the display of the word "Yes" (string expression of the logical value True).

PageReplace

PReplace (<Строка>, <ПодстрокаПоиска>, <ПодстрокаЗамены>) ... Finds all occurrences of the search substring in the original string and replaces it with the replacement substring.

Example 16. In the line "Hello World!" replace the word "Peace" with the word "Friends".

String = StrReplace ("Hello World!", "World", "Friends"); Report (String);

The result of the execution of this code will be the display of the line "Hello Friends!"

StrNumberStrings

StrNumber of Lines (<Строка>) ... Counts the number of lines in a multi-line string. To move to a new line in 1s 8, use the character PS(line feed character).

Example 17. Determine the number of lines in the text:
"First line
Second line
Third line "

Number = StrNumberStrings ("First line" + Symbols.PS + "Second line" + Symbols.PS + "Third line"); Report (Number);

The result of executing this code will be the display of the number of lines in the text: 3

StrGetString

StrGetString (<Строка>, <НомерСтроки>) ... Gets a string in a multi-line string by its number. Line numbering starts at 1.

Example 18. Get the last line in the text:
"First line
Second line
Third line "

Text = "First line" + Symbols.PS + "Second line" + Symbols.PS + "Third line"; LastRow = StrGetString (Text, StrNumberLines (Text)); Report (LastLine);

The result of the execution of this code will be the display of the line "Third line".

StrNumber of Occurrences

StrNumber of Occurrences (<Строка>, <ПодстрокаПоиска>) ... Returns the number of occurrences of the specified substring in a string. The function is case sensitive.

Example 19. Determine how many times the letter "c" appears in the line "Lines in 1s 8.3 and 8.2", regardless of its case.

Line = "Lines in 1s 8.3 and 8.2"; Number of Occurrences = StrNumber of Occurrences (Vreg (String), "S"); Report (Number of Occurrences);

The result of executing this code will be the display of the number of occurrences: 2.

PageStarts With

PageStarts With (<Строка>, <СтрокаПоиска>) ... Checks if the string passed in the first parameter starts with the string in the second parameter.

Example 20. Determine whether the INN of the selected counterparty begins with the number 1. Let in the variable Counterparty Contractors.

TIN = Counterparty.INN; Starts withUnits = StrStarts with (INN, "1"); If BeginsUnits Then // Your Code EndIf;

PageEnds With

PageEnds With (<Строка>, <СтрокаПоиска>) ... Checks if the string passed in the first parameter ends with the string in the second parameter.

Example 21. Determine whether the TIN of the selected counterparty ends with the digit 2. Let in the variable Counterparty a link to a directory item is stored Contractors.

TIN = Counterparty.INN; Ends With Two = Str Ends With (INN, "2"); If Ends WithDouble Then // Your code EndIf;

PageSplit

StrSplit (<Строка>, <Разделитель>, <ВключатьПустые>) ... Splits a string into parts using the specified delimiter characters and writes the resulting strings to an array. The first parameter stores the original string, the second contains the string containing the separator, the third specifies whether to write empty strings to the array (by default True).

Example 22. Suppose we have a string containing numbers separated by ";", get an array of numbers from the string.

String = "1; 2; 3"; Array = StrSplit (String, ";"); For Rd = 0 By Array.Quantity () - 1 Cycle Attempt Array [Rd] = Number (AbbrLP (Array [Rd])); Exception Array [Сч] = 0; End of Attempts End of Loop;

As a result of execution, an array with numbers from 1 to 3 will be obtained.

StrConnect

StrConnect (<Строки>, <Разделитель>) ... Converts an array of strings from the first parameter to a string containing all the elements of the array, separated by the delimiter specified in the second parameter.

Example 23. Using the array of numbers from the previous example, get the original string.

For Rd = 0 By Array.Quantity () - 1 Cycle Array [Rd] = String (Array [Rd]); End of Cycle; String = StrConnect (Array, ";");

The "String" type is found in all programming languages. It is primitive, and in 1C there are many functions for working with it. In this article, we will take a closer look at various ways of working with string types in 1C 8.3 and 8.2 using examples.

Line

In order to convert a variable of any type into a string, there is a function of the same name "String ()". The input parameter will be the variable itself, the string representation of which is to be obtained.

String (False) // returns "No"
String (12345) // returns "12 345"
String (CurrentDate ()) // 07/21/2017 11:55:36 ″

It is possible to convert not only primitive types to a string, but also others, for example, elements of reference books, documents.

SocrLP, SocrL, SocrP

The input parameters of these functions are a string type variable. Functions remove insignificant characters (spaces, carriage returns and others): from the left and right sides, only from the left side, and only from the right, respectively.

AbbrLP ("Spaces on both sides will be removed") // "Spaces on both sides will be removed"
Abbreviated ("Spaces on both sides will be removed") // "Spaces on the left will be removed"
Abbreviation ("Spaces on both sides will be removed") // "Spaces on the right will be removed"

Leo, Right, Wednesday

These functions allow you to trim part of a string. The "Lion ()" function will return the part of the string from its left side of the specified length. The "Right ()" function is the same, but the cropping is done on the right. The "Avg ()" function allows you to specify the number of the character from which the string will be selected and its length.

Lion ("String variable", 4) // returns "Stro"
Right ("String variable", 7) // returns "variable"
Wed ("String variable", 2, 5) // returns "troco"

Str Length

The function determines the number of characters that are contained in the string variable.

StrLength ("Word") // execution result will be number 5

Find

The function makes it possible to search for a part of a string in any string variable. The return value will be a number that shows the position of the beginning of the found string. If no match is found, zero is returned.

Please note that searches are case sensitive. If the original string contains more than one occurrence of the search substring, the function will return the beginning of the first occurrence.

Find ("one, two, one, two, three", "two") // the function will return the number 6

Empty line

Using this function allows you to determine if a string is empty. Insignificant characters such as space, carriage return, and others are ignored.

EmptyString ("Pupkin Vasily Ivanovich") // the function will return the value False
EmptyString ("") // function will return True

VReg, NReg, Treg

These functions are very useful for comparing and converting string variables. Breg () will return the original string in uppercase, HPreg () in lowercase, and TPreg () will format it so that the first character of each individual word will be capitalized and all subsequent ones will be lowercase.

Vreg ("GENERAL DIRECTOR") // return value - "GENERAL DIRECTOR"
НReg ("GENERAL DIRECTOR") // return value - "general director"
TREG ("GENERAL DIRECTOR") // return value - "General Director"

PageReplace

This function is analogous to replacement in text editors. It allows you to substitute one character or set of characters for another in string variables.

StrReplace ("red, white, yellow", ",", ";") // will return "red; White; yellow"

StrNumberStrings

The function allows you to determine the number of lines separated by carriage returns in a text variable.

The loop in the example below will go through three circles because the RowNumber of Rows function will return a value of 3:

For ind = 1 by StrNumber of Lines ("String1" + Symbols.PS + "String2" + Symbols.PS + "String3") Loop
<тело цикла>
End of Cycle;

StrGetString

This function works with multi-line text in the same way as the previous one. It allows you to get a specific string from a text variable.

StrGetString ("String1" + Symbols.PS + "String2" + Symbols.PS + "String3", 2) // will return "String2"

StrNumber of Occurrences

The function counts the number of occurrences of a character or substring in the search string.

StrNumber of Attachments ("a; b; c; d;", ​​";") // the function will return the number 4

Symbol and Symbol Code

These functions allow you to get a character by its Unicode code, as well as to determine this code by the character itself.

SymbolCode ("A") // the function will return the number 1 040
SymbolCode (1040) // the function will return "A"

Frequent tasks when working with strings

Concatenating strings

To concatenate multiple strings (to perform concatenation), it is sufficient to use the addition operator.

"Line 1 ″ +" Line 2 ″ // the result of adding two lines will be "Line 1 Line 2"

Type conversion

In order to convert a type to a string, for example, a reference to a dictionary item, a number, etc., it is enough to use the "String ()" function. Functions like "Abbreviation ()" will also convert variables to a string, but immediately with the truncation of insignificant characters.

String (1000) // will return "1000"

Please note that when converting a number to a string, the program automatically added a space separating a thousand. In order to avoid this, you can use the following constructions:

StrReplace (String (1000), Characters.NPP, "") // will return "1000"

String (Format (1000, "CHG =")) // will return "1000"

Quotes in a string

Quite often, you will have to deal with the need to specify quotation marks in a string variable. It can be either a request text written in the configurator, or just a variable. To solve this problem, you just need to set two quotation marks.

Title = String ("Horns and Hooves LLC" "is us!") // returns "Horns and Hoofs LLC" is us! "

Multiple lines, line break

In order to create multi-line text, it is enough to add line break characters (Symbols.PS) to it.

MultilineText = "First line" + Symbols.PS + "Second line"

How to remove spaces

In order to remove spaces to the right or to the left, you can use the function "Abbreviation ()" (as well as "Abbreviation ()" and "Abbreviation ()"):

StringNoSpaces = AbbreviatedLP ("Many letters") // the function will return the value "Many letters"

If, after converting a number to a string, you need to remove non-breaking spaces, use the following construction:

StringNoSpaces = StrReplace (String (99999), Characters.NPP, "") // will return "99999"

Also, programmers often use the following construction, which allows you to remove or replace all spaces of a text variable with another character:

StringNoSpaces = StrReplace ("welcome", "", "") // returns "hello"

Comparing strings to each other

The terms can be compared with the usual equal sign. The comparison is case sensitive.

"Hello" = "hello" // will return False
"Hello" = "Hello" // will return True
"Hello" = "Goodbye" // will return False