1c 8.2 the serial number of the character in the string. New functions for working with strings. Format function StrTemplate()

PART 1. METHODS (26).

1.1. Basic methods (10). Independent, built on their simple algorithms.

Str_Complete() (right-left padding with specified characters).

Str_Inverse () (inversion - characters from right to left).

Str_Codes() (character codes through ”,” and an array with codes)

Str_Symbols() (string from codes separated by ”,” or from an array with codes)

Str_ReplaceCharacters() (replacing one character with another).

Str_FromArray() (string from the array of fragments separated by a separator)

Str_FindIn() (search for a substring (including on the right) with the specified entry number).

Str_FindGr() (Search for a group of characters included in the specified character set)

Str_FindNumber() (Search for a number, including on the right with the specified occurrence number)

Str_Interpret() (to an array, according to the established syntax)

1.2. Derived methods (12). Actually, this is the use of four generalized methods-algorithms (see Part 2)

Str_Number() (from the beginning and from the end of the string, do not be "afraid" of non-digit characters.

Str_Find() (search for a substring (including case-insensitive and on the right) with the specified entry number).

Str_Replace() (search (including case insensitive and on the right), and replace delimiter substrings).

Str_Piece() (a piece of string between the specified occurrences of the delimiter (left or right)).

Str_ReplacePiece() (replacement in the source string "piece" with the specified string).

Str_VArray() (between the specified occurrences of the delimiter (including on the right and without case).

Str_MoveBySyllables() (split into substrings "Hard", with a hyphen).

Str_MoveWords() (split into substrings “Softly”)

Str_Cut() (“Cut” into substrings of specified lengths)

Str_Short() (replace the left group of "reduced" characters with a "replacement string"

Str_Short() (replace the right group of "reduced" characters with a "replacement string"

Str_Short() (replace in the middle of a group of "reduced" characters with a "replacement string"

Str_Expand (expansion to specified length by increasing the number of specified characters)

1.3. Detailed methods (3). "Preparation" of a line with transfer to a table with detailed information.

Str_inTableIn() (to the table according to the system of nested separators).

Str_inTableGroup (to the table according to the multilevel filter).

Str_inTableNumbers (into a table with numbers and fragments between them).

PART 2. GENERALIZED METHODS-ALGORIMS (3).

Str_Entry() (methods ”Find” and ”Replace”).

Str_Fragments() (methods “Piece”, “ReplacePiece”, “ToArray”, “ToTableIn”).

Str_Short() (methods "Short", "ShortP", "Short", "Expand".

Str_Split() (methods “Move By Syllables”, “Move By Words”, “Cut”).

PART 3. UNIVERSAL FUNCTION.

It is a kind of conditional programming interface that allows

apply several methods to a string at once. Implemented as

functions with seven parameters ("Demo" is built on this function):

Str_(Methods, Submethods, Input, Param1, Param2, Length_Position_Number, AdditionalOutput)

Options:

- “Methods” - several “combined” and (or) one “exclusive” method

(single-character codes or names, possible through ",")

- ”Submethods” - several ”combinable” and (or) “exclusive” options

“exclusive” method (single-character codes or names);

- “Input” - String, or Array or Table of values;

- “Param1” - search string, substitutions, delimiters, filters;

- “Param2” - replacement string or symbols;

- “Length_Number_Position” -Number, Numbers through a separator or an array with Numbers;

- “Exit” - Number or String or Array or Table of Values;

Names and (or) one-character Codes of methods-submethods, as well as numbers in

(Length_Position_Number) can be in any case and separated

any of the following delimiters: ”, :;”.

PART 4. SOME EXAMPLES.

HaveNumbersINString=(Str_FindNumbers(InString)<>Undefined);

HaveDigitsINString=(Str_FindGr(InString,"+0123456789")>0);

ThereLatin=(Str_FindGr(VxStr, Str_Interpret("lL"))>0);

HaveSpecifiedSigns=(Str_NfindGr(VxStr, "+ to hornYu.0p9")>0);

IsUnprintable=(Str_FindGr(VxStr, Str_Interpret("-l-L-r-R-P-Z-C"))>0);

PART 5. CONCLUSION.

Where possible, managed with one pass along the line. The second pass - usually already in fragments. Did not use the built-in StrNumberOccurrences() function.

Built-in functions used: Left(),Right()Mid(),StrLength()

- (positioning and retrieving part of a string -should be "fast").

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

String addition

The "+" operator is used to add strings in a query. You can only add strings of limited length.

SELECT "Name: " + Contractors.Name AS Column1 FROM Directory.Contractors AS Contractors WHERE Contractors.Reference = &Reference

Substring function

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

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

If the string length is less than 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. Instead, it is better to use the cast operator EXPRESS().

Function Similar

If we need to make sure that the 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 a more subtle comparison is needed? Not just for equality or inequality, but for similarity to a certain pattern? That's exactly what the LIKE function was created for.

LIKE - An operator to check if a string is similar to 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 value of the expression matches the template, the result of the operator will be TRUE, otherwise it will be FALSE.

The following characters in the template string are service characters and have a different meaning from the string character:

  • % (percentage): a sequence containing any number of arbitrary characters;
  • _ (underscore): one arbitrary character;
  • […] (one or more characters within square brackets): any single character listed inside square brackets. An enumeration can contain ranges, such as a-z, meaning any character within 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 following the negation sign.

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

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 work with string types in 1C 8.3 and 8.2 with examples.

Line

In order to convert a variable of any type to a string, there is the "String ()" function of the same name. 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()) //"21.07.2017 11:55:36"

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

Abbreviated LP, Abbreviated L, Abbreviated P

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

abbrl("Spaces on both sides will be removed") // "Spaces on both sides will be removed"
abbr("Spaces on both sides will be removed") // "Spaces on the left will be removed"
abbr(" Spaces on both sides will be removed ") // "Spaces on the right will be removed"

Leo, Right, Middle

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

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

StrLength

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

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

Find

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

Note that the search is case sensitive. If there is more than one occurrence of the search substring in the original string, 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 not taken into account.

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

VReg, NReg, TReg

These functions are very useful when comparing and converting string variables. "Vreg()" will return the original string in uppercase, "HReg()" in lowercase, and "TReg()" will format it so that the first character of each individual word is capitalized, and all subsequent characters are lowercase.

VReg("GENERAL DIRECTOR") // return value - "GENERAL DIRECTOR"
HReg("GENERAL DIRECTOR") // return value - "CEO"
TReg("GENERAL DIRECTOR") // return value - "General Director"

StrReplace

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

StrReplace("red, white, yellow", ",", ";") // returns "red; white; yellow"

StrNumberRows

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

The loop in the example below will go through three circles because the StrNumberRows function will return the value 3:

For ind \u003d 1 by StrNumber of Lines ("Line1" + Symbols.PS + "String2" + Symbols.PS + "Line3") Loop
<тело цикла>
EndCycle;

StrGetString

This function works with multiline 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) // returns "Line2"

StrNumberOccurrences

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

StrNumberInstallations("a;b;c;d; ", ";") // the function will return the number 4

Symbol and SymbolCode

These functions allow you to get a character by its Unicode code, as well as 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

String Concatenation

To concatenate multiple strings (concatenate) just 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 element, a number, and so on, it is enough to use the "String ()" function. Functions like "ShortLP()" will also convert variables to a string, but immediately with cutting off insignificant characters.

String(1000) // will return "1000"

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

StrReplace(String(1000),Characters.NPP,"") // returns "1000"

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

Quotes in a string

Quite often you will have to deal with the need to put quotes 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 quote characters.

Header = String("Horns and Hooves LLC is us!") // returns "Roga and Hooves LLC is us!"

Multiline, line break

In order to create multiline text just add line break characters to it (Symbols.PS).

MultilineText = "First Line" + Characters.PS + "Second Line"

How to remove spaces

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

StringWithoutSpaces = ShortLP(" 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:

StringWithoutSpaces = StrReplace(String(99999),Characters.NPP,"") // returns "99999"

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

StringWithoutSpaces = StrReplace(" hello", " " ,"") // returns "hello"

Comparing strings to each other

You can compare terms 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

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. New functions will be convenient and useful in technological tasks of text analysis. In tasks related to the parsing of text that contains data in a formatted form. This may be the analysis of some files received from the equipment, or, for example, the analysis of a technological log.

All the actions that the new functions perform, you could perform before. With the help of more or less complex algorithms written in an embedded language. Therefore, new functions do not give you any fundamentally new opportunities. However, they allow you to reduce the amount of code, make the code simpler and more understandable. In addition, 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 the built-in language.

Format function StrTemplate()

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:

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

<Шаблон>is the string in which to substitute the parameter representations.

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

To specify a specific place in the template to which you want to perform the substitution, you need to use markers of the form %1, ... %10. The number of markers involved in the template and the number of parameters containing values ​​must match.

For example, the result of executing such an operator:

there will be a line:

Data error on line 2 (requires Date type)

String Function StrCompare()

This function compares two strings case insensitively. For example, like this:

You could perform the same action before using the ValueComparison object:

However, using the new function looks simpler. And besides, the function, unlike the Value Compare object, works both in the thin client and in the web client.

String Functions StrBeginsC(), StrEndsTo()

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

For example, they are convenient to use in the If statement:

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

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, a technological log. For example, you can easily disassemble a technological log entry into parts suitable for further analysis:

Function of working with strings StrFind()

Instead of the old Find() function, we implemented new feature, which has additional features:

  • Search in different directions (from the beginning, from the end);
  • Search from the 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. The old Find() function is recommended not to be used anymore.

Below is an example using the new search capabilities. Searching backwards is useful when you need the last fragment of a formalized string, for example, full name file in URL. And searching from a specified position helps in cases where you need to search in a known fragment, and not in the entire string.

TO basic capabilities programming languages ​​usually include work with numbers and strings. Usually these features are hardwired into the compiler code (or "base" classes of the programming language are implemented).

In 1C, the capabilities of working with strings are programmed in the platform itself. Today we will consider the features of working with 1C strings in programs in the built-in 1C language.

Line value 1C

1. Let's start with the simplest. Creating a variable and assigning a string constant value to it looks like this in 1C:

Variable = "Hello world!";

If you want to specify a quote character in a constant string value 1C, then you need to double it ""

Variable = "Hello, "world""!";

2. Line break 1C can be specified in two ways at once. The first is using the symbol |

Variable = "Hello,
| world! ";

The second is using the Symbols system enum. It allows you to add both a line break 1C and other non-printable characters, such as TAB.

Variable = "Hi" + Symbols.ps + "peace!";

3. Configurations in 1C can be developed not only for one language (Russian, English or other) - but simultaneously for several languages. In this case, the currently used language is selected at the bottom of the 1C window.

The list of languages ​​is located in the configuration window in the General/Languages ​​branch. Each language has a short identifier such as en or eng.

It is clear that when programming such a configuration, 1C lines can also be multilingual. To do this, it is possible to create such a 1C line by specifying through; options by language ID:

Variable = "ru=""Hello, world!""; en=""Hello, world! """;

If you use the 1C line formed in this way as usual, then it will be what is written in it. In order for the system to split it into two options and use the desired one, you must use the NStr() function:

//correct for bilingual configurations
Report(NStr(Variable));

Props with line type 1C

The requisite is a field of the directory / document 1C. It differs from a variable in a program in the 1C language in that its type is precisely indicated for the attribute (number, string 1C, etc.). If you need to brush up on what props are, check out the tutorial on .

If you specify the attribute type - line 1C, then you must additionally specify the parameters.

1C strings are of unlimited length (indicated as length = 0) and limited length, indicating the exact number of characters. 1C strings of unlimited length are stored in a separate SQL table, so their use is less productive than limited ones.

That is why the use of 1C strings of unlimited length has its limitations - it is not possible to use them everywhere. For example, it is not possible as a document number, directory code, measurement.

Working with 1C lines

To work with strings, there are several built-in functions of the 1C platform.

  • AbbrLP("Unbelievable, but true!")
    Removes extra spaces from string 1C. It can also be used to convert any type to a 1C string (for example, numbers).
  • Variable = "Vasya" + Abbrl("plus") + "Olya"; //will be "Vasya plus Olya"
    An example of summing several string values ​​1C. The result is one line 1C.
  • Variable = Lion("Music", 2); // will be "Mu"
    Variable = Avg("Music", 2, 2); // will be "ps"
    Variable = Rights("Music", 2); // will be "ka"
    Various options for obtaining a substring from a string 1C.
  • Variable = Find("Music", "ps"); //will be 3
    Search for a substring in string 1C, starting with character 1.
  • Variable = StrLength("Music"); //will be 6
    Returns the number of characters in a string 1C.
  • Notify("Hi") //in the message box at the bottom of the 1C window
    alert("hello") //popup dialog
    Status("Hello") //in the status display line at the bottom left
    .

Bringing objects to line 1C

As you know, the most popular format for the exchange of structured information at present is XML. Even latest version MS Office Word and Excel save files in this format (docx and xlsx respectively, change the extension to zip, open in an archiver).

The 1C platform for data exchange provides several options, the main of which is also XML.

1. The simplest method is to use the ShortLP() or String() function. You can use the REPRESENTATION() function in the query text. The result of their action is the same - they generate a string representation of any 1C object for the user.

For the default directory, this will be its name. For a document, the document name, number, and date.

2. Any 1C object (with restrictions) can be converted to XML and vice versa. The conversion process is called serialization.

ViewStringXml = XMLString(Value); //get XML from value 1C
Value1С = XMLValue(Type("CatalogReference.Nomenclature"),ViewStringXml); //get the 1C value from the XML string, you must specify the type of 1C that should be received

3. There is a native way of the 1C platform to convert any 1C object into a string. It migrated from version 1C 7.7. This format is not understood by other programs, but understands another 1C, which makes it easy to use it to exchange between 1C databases.

String = ValueInStringInt(Value1S); //get string 1C from value 1C
ValueToFile("C:\MyFile.txt", Value1C); //another option, we get a file with a saved string from the value 1C
Value1C = ValueFromStringInt(String); //back from line 1C
Value1C = ValueFromFile("C:\MyFile.txt"); //back from file

Editing lines 1C on the form

In addition to working with 1C strings in a 1C program, of course, I would like the user to be able to edit them. There are several possibilities for this:

1. The easiest way is to request the input of the 1C line on demand. This method is used when teaching 1C programming, in life it is used much less often (but it is used!).

Variable = "";
String = EnterValue(Variable, "Enter full name");

2. To display the details of the 1C object (directory / document) or the details of the form (see), the input field is most often used. This is the most common tool in 1C for the user to work with editing fields.

3. The possibilities of the input field can be expanded (see the properties of the input field, right click on it, for more details):

  • Checkbox Multiline editing mode
  • Advanced editing checkbox (available if the previous checkbox is checked)
  • Checkbox Password mode (see ).

4. If all the possibilities of the input field are not enough for you, there is a built-in editor. To add it to the form, you need to add a Field in the menu Form / Insert control text document. In its properties, you can specify the mode of its operation - the Extension property.

A text document field cannot be linked directly to data. It is necessary to write the following function in the event handler of the OnOpening() form (see ):

FormElements.ElementNameTextDocumentField.SetText(StringValue); //here, ValueString is the text received, for example, from the attribute

And in the save handler - for example, in the Save button - add a save:

ValueString = FormElements.ElementNameTextDocumentField.GetText(); //ValueString here is the props where we save the value

5. In 1C version 8.2.11, in managed forms, appeared new opportunity line representation 1C - Formatted document field.


Similar to the field of a text document, it is necessary to set when opening and write when saving the text yourself using the program.

  • In the 1C object, the form of which we are making (reference book, document, processing, etc.) - add an attribute with the Value Storage type
  • In the OnReadOnServer() function, set the text from the attribute

    //here Requisite is the added attribute of the 1C object
    //here FormattedDocument is the name of the field on the edit form
    &On server

    FormattedDocument = CurrentObject.Attributes.Get();
    EndProcedure

  • In the BeforeWriteOnServer() function or by pressing the button, write the text from the field

    &On server
    Procedure OnReadingOnServer(CurrentObject)
    CurrentObject.Attributes = NewValueStorage(FormattedDocument);
    EndProcedure