Inserting a substring into a string. Forming a new symbol using a Blend transition

Working with Strings and Characters

Text processing is one of the most common programming tasks. If you need to process any text data, then you simply cannot do without knowledge of the material that will be presented below. Especially if the data was generated not by you personally, but by some third party program or another person.

Symbols

A character is one unit of text. This is a letter, a number, some kind of sign. The character code table consists of 256 positions, i.e. each character has its own unique code from 0 to 255. A character with a certain code N is written like this: #N. This is exactly how the symbols are indicated in the program code. Since the symbol code is a number no more than 255, it is obvious that the symbol occupies 1 byte in memory. As you know, there is no dimension less than a byte. More precisely, it exists - it is a bit, but we cannot work with bits in the program: byte - minimum unit. You can view the table of symbols and their codes using standard utility"Character table" included in Windows (the shortcut is located in the Start menu - Programs - Accessories - System Tools). But very soon we will write something similar ourselves.

Strings

A string, also known as text, is a set of characters, any sequence of them. Accordingly, one character is also a string, also text. Text string has a certain length. The length of a string is the number of characters it contains. If one character takes up 1 byte, then a string of N characters takes up N bytes.

There are other code tables in which 1 character is represented not by one byte, but by two. This is Unicode. The Unicode table contains characters from all languages ​​of the world. Unfortunately, working with Unicode is quite difficult and its support is so far only local. Delphi does not provide Unicode capabilities. Software part yes, but here are the visual elements - forms, buttons, etc. cannot display text in Unicode format. Let's hope that such support will appear in the near future. 2 bytes are also called a word. Hence the name of the corresponding numeric data type - Word (a number that occupies 2 bytes in memory, values ​​​​from 0 to 65535). The number of “cells” in the Unicode table is 65536 and this is quite enough to store all the languages ​​of the world. If you decide that “1 byte - 256 values, then 2 bytes - 2 * 256 = 512 values,” I advise you to remember the binary system and the principle of data storage in a computer.

Data types

Let's move on directly to programming. There are corresponding data types for working with characters and strings:

· Char - one character (i.e. 1 byte);

· String - character string, text (N bytes).

Officially, strings can only hold 255 characters, but in Delphi you can write much more per string. To store large texts and texts with special characters, there are special data types AnsiString and WideString (the latter, by the way, is two-byte, i.e. for Unicode).

To specify text values ​​in Pascal, single quotes are used (not double quotes!). Those. When you want to assign a value to a string variable, you should do it like this:

The characters are specified in the same way, only there is a single character in the quotes.

If you want to strictly limit the length of the text stored in a string variable, you can do it like this:

Since each line is a sequence of characters, each character has its own serial number. In Pascal, the numbering of characters in lines starts from 1. I.e. in the string "ABC" the character "A" is the first, "B" is the second, etc.

The serial number of a character in a line was not invented by chance, because it is by these numbers, indices, that actions are carried out on the lines. You can get any character from a string by specifying its number in square brackets next to the variable name. For example:

var s: string; c:char; ... s:="Hello!"; c:=s; //c = "e"

A little later, when we study arrays, it will become clear that a string is an array of characters. This implies the form of addressing individual symbols.

String Processing

Let's move on to the functions and procedures for processing strings.

The length of a string can be found using the Length() function. The function takes a single parameter - a string, and returns its length. Example:

var Str: String; L: Integer; ( ... ) Str:="Hello!"; L:=Length(Str); //L = 6

Finding a substring in a string

An inherent task is to find a substring in a string. Those. the problem is formulated as follows: there is a string S1. Determine from what position the string S2 enters it. It is impossible to imagine any processing without performing this operation.

So, for such a finding there is a Pos() function. The function takes two parameters: the first is the substring that needs to be found, the second is the string in which to search. The search is carried out taking into account the case of characters. If the function finds an occurrence of a substring in a string, it returns the position number of its first occurrence. If no entry is found, the function returns 0. Example:

var Str1, Str2: String; P: Integer;( ... ) Str1:="Hi! How do you do?"; Str2:="do"; P:=Pos(Str2, Str1); //P = 9

Removing part of a line

You can delete part of a string using the Delete() procedure. It should be noted that this is a procedure, not a function - it performs actions directly on the variable that is passed to it. So, the first parameter is a variable of string type from which the fragment is removed (namely a variable! specific meaning is not specified, because the procedure does not return a result), the second parameter is the number of the character from which the fragment should be deleted, the third parameter is the number of characters to delete. Example:

var Str1: String; ( ... ) Str1:="Hello, world!"; Delete(Str1, 6, 7); // Str1 = "Hello!"

It should be noted that if the length of the deleted fragment is greater than the number of characters in the line, starting from the specified position (i.e., “let’s go beyond the edge”), the function will work normally. Therefore, if you need to remove a fragment from a string from some character to the end, you do not need to calculate the number of these characters. The best way will set the length of this string itself.

Here's an example. Let's say you want to find the first letter "a" in a string and delete the part of the string that follows it. Let's do it as follows: we find the position of the letter in the line using the Pos() function, and delete the fragment using the Delete() function.

var Str: String; ( ... ) Str:="This is a test."; Delete(Str,Pos("a",Str),Length(Str));

Let's try to substitute the values ​​and see what is passed to the Delete function. The first letter "a" in the line is at position 9. The length of the entire line is 15 characters. So the function call goes like this: Delete(Str,9,15). It can be seen that from the letter "a" to the end of the line there are only 7 characters... But the function will do its job, despite this difference. The result, of course, will be the string "This is". This example simultaneously showed a combination of several functions.

Copying (extracting) part of a string

Another important task is copying part of a string. For example, extracting individual words from text. You can select a fragment of a line by removing unnecessary parts, but this method is inconvenient. The Copy() function allows you to copy a specified part from a string. The function takes 3 parameters: text (string) from which to copy, the number of the character from which to copy and the number of characters to copy. The result of the function will be a string fragment.

Example: suppose you want to select the first word from a sentence (the words are separated by a space). On the form we will place Edit1 (TEdit), into which the sentence will be entered. The operation will be performed by pressing a button. We have:

In this case, a fragment from the beginning to the first space is copied from the string. The number of characters is taken to be one less, because otherwise the space will also be copied.

Inserting a substring into a string

If you want to insert another string into an existing string, you can use the Insert() procedure. The first parameter is the line to be inserted, the second is a variable containing the line where you want to insert, the third is the position (character number) starting from which the line will be inserted. Example:

procedure TForm2.Button1Click(Sender: TObject); var S: String; begin S:="1234567890"; Insert("000",S,3); ShowMessage(S) end;

In this case, the result will be the string "1200034567890".

"More serious" example

The examples above only demonstrate the principle of working with strings using the Length(), Pos(), Delete() and Copy() functions. Now let's solve a more complicated problem, which will require the combined use of these functions.

Task: break the text entered into the Memo field into words and display them in the ListBox, one per line. Words are separated from each other by spaces, periods, commas, exclamation marks and question marks. In addition, display the total number of words in the text and the longest of these words.

That's right... The task is not at all easy. First, you should immediately realize that you need to use loops. There is no way without them, because we do not know what text will be transferred to the program for processing. Secondly, words are separated by different symbols - this creates additional difficulties. Well, let's go in order.

Interface: Memo1 (TMemo), Button1 (TButton), ListBox1 (TListBox), Label1, Label2 (TLabel).

First, let's transfer the entered text to a variable. In order to take all the text from Memo at once, let's turn to the Lines.Text property:

var Text: string; begin Text:=Memo1.Lines.Text; end;

Now let's move on to processing. The first thing you need to do is deal with delimiter characters. The fact is that such symbols can easily come in a row, because after commas, periods and other characters there is a space. You can get around this difficulty like this in a simple way: replace all separating characters with one, for example a comma. To do this, let's go through all the characters and make the necessary replacements. To determine whether a character is a delimiter, we write all the delimiters into a separate string variable (constant), and then search for each character in this string using the Pos() function. All these replacements will be made in a variable so that the original text in the Memo (i.e. on the screen) is not affected. However, to check the intermediate results of the work, it makes sense to output the processed text somewhere. For example, to another Memo field. To go through all the characters, we’ll use a FOR loop, where the variable will go through the serial numbers of all the characters, i.e. from 1 to the length of the text line:

procedure TForm1.Button1Click(Sender: TObject); const DelSym = ".,!?"; var Text: string; i:integer; if Pos(Text[i],DelSym) > 0 then Text[i]:=","; Memo2.Text:=Text; end;

Now we need to eliminate the interference. Firstly, the first character should not be a delimiter, i.e. if the first character is a comma, it must be removed. Next, if there are several commas in a row, they need to be replaced with one. Finally, to process all text correctly, the last character must be a comma.

if Text = "," then Delete(Text,1,1); while Pos(",",Text) > if Text<>"," then Text:=Text+",";

Here the replacement is made as follows: a cycle is organized in which one of the commas is removed, but this happens as long as there are two consecutive commas in the text.

Well, now there is nothing superfluous left in the text - only words separated by commas. First, we will ensure that the program extracts the first word from the text. To do this, we will find the first comma, copy the word from the beginning of the text to this comma, and then delete this word from the text along with the comma. The deletion is done so that you can then, after performing the same operation, cut out the next word.

var Word: string; (...)

Now in the Word variable we have a word from the text, and in the Text variable we have the rest of the text. The cut word is now added to the ListBox by calling ListBox.Items.Add(line_to_add).

Now we need to organize a loop that would allow us to cut out all words from the text, and not just the first one. In this case, REPEAT is more suitable than WHILE. The condition should be Length(Text) = 0, i.e. end the loop when the text becomes empty, i.e. when we cut all the words out of it.

repeat Word:=Copy(Text,1,Pos(",",Text)-1); Delete(Text,1,Length(Word)+1); ListBox1.Items.Add(Word); until Length(Text) = 0;

So on this moment we have:

procedure TForm1.Button1Click(Sender: TObject); const DelSym = ".,!?"; var Text,Word: string; i:integer; begin Text:=Memo1.Lines.Text; for i:= 1 to Length(Text) do if Pos(Text[i],DelSym) > 0 then Text[i]:=","; if Text = "," then Delete(Text,1,1); while Pos(",",Text) > 0 do Delete(Text,Pos(",",Text),1); repeat Word:=Copy(Text,1,Pos(",",Text)-1); Delete(Text,1,Length(Word)+1); ListBox1.Items.Add(Word); until Length(Text) = 0; end;

If you run the program now, you will see that everything works fine. Except for one thing - some empty lines appeared at the end of the ListBox... The question arises: where did they come from? You will learn about this in the next section of the lesson, but for now let's implement what is required to the end.

The number of words in the text is very easy to determine - you don’t need to write anything again. Because We have words listed in the ListBox; it’s enough to simply find out how many lines there are - ListBox.Items.Count.

Now you need to find the longest of all words. The algorithm for finding the maximum number is as follows: we take the first of the numbers as the maximum. Then we check all other numbers in this way: if the number is greater than the one currently written as the maximum, we make this number maximum. In our case, we need to look for the maximum word length. To do this, you can add code to a loop of cutting words from the text or perform a search after adding all the words to the ListBox. Let's do it the second way: organize a loop through the ListBox lines. It should be noted that lines are numbered from zero, not from one! We will store the most in a separate variable long word. It would seem that we also need to store the maximum length of the word so that we have something to compare with... But there is no need to create a separate variable for this, because we can always find out the length of the word using the Length() function. So let's say the first word is the longest...

Why loop up to ListBox.Items.Count-1, and not just up to Count, figure it out yourself :-)

Now everything is ready!

procedure TForm1.Button1Click(Sender: TObject); const DelSym = ".,!?"; var Text,Word,LongestWord: string; i:integer; begin Text:=Memo1.Lines.Text; for i:= 1 to Length(Text) do if Pos(Text[i],DelSym) > 0 then Text[i]:=","; if Text = "," then Delete(Text,1,1); while Pos(",",Text) > 0 do Delete(Text,Pos(",",Text),1); Text:=AnsiReplaceText(Text,Chr(13),""); Text:=AnsiReplaceText(Text,Chr(10),""); repeat Word:=Copy(Text,1,Pos(",",Text)-1); Delete(Text,1,Length(Word)+1); ListBox1.Items.Add(Word); until Length(Text) = 0; Label1.Caption:="Number of words in the text: "+IntToStr(ListBox1.Items.Count); LongestWord:=ListBox1.Items; for i:= 1 to ListBox1.Items.Count-1 do if Length(ListBox1.Items[i]) > Length(LongestWord) then LongestWord:=ListBox1.Items[i]; Label2.Caption:="Longest word: "+LongestWord+" ("+IntToStr(Length(LongestWord))+" letters)"; end;

Working with Symbols

Actually, working with symbols comes down to using two main functions - Ord() and Chr(). We have already met with them. The Ord() function returns the code of the specified character, and the Chr() function, on the contrary, returns the character with the specified code.

Remember the "Symbol Table"? Let's do it ourselves!

The output will be carried out in TStringGrid. This component is a table where each cell contains text value. The component is located on the Additional tab (by default it comes right after Standard). First of all, let's set up our sign. We need only two columns: in one we will display the symbol code, and in the other - the symbol itself. The number of columns is set in a property with the logical name ColCount. Set it to 2. By default, StringGrid has one fixed column and one fixed row (they are displayed in gray). We don’t need a column, but a row is very useful, so we set FixedCols = 0, and leave FixedRows = 1.

Filling will be carried out directly when starting the program, i.e. We won't install any buttons. So, let's create a handler for the OnCreate() event of the form.

Number of characters in code table 256, plus the header - a total of 257. Let's set the number of lines programmatically (although you can also set it in the Object Inspector):

procedure TForm1.FormCreate(Sender: TObject); begin StringGrid1.RowCount:=257; end;

The conclusion is made extremely simply - using a loop. We simply go through the numbers from 0 to 255 and display the corresponding symbol. We also display the inscriptions in the header. StringGrid cells are accessed using the Cells property: Cells[column_number, row_number]. Column and row numbers (starting from zero) are indicated in square brackets. Values ​​are text.

Let's launch and take a look.

Special symbols

If you look closely at our table, you will see that many of the symbols appear as squares. No, these are not icons. This is how characters that do not have a visual display are displayed. Those. a symbol, for example, with code 13 exists, but it is invisible. These symbols are used for additional purposes. For example, the character #0 (that is, the character with code 0) is often used to indicate the absence of a character. There are also strings called null-terminated - these are strings ending with the #0 character. Such strings are used in the C language.
Keystrokes can be identified by codes. For example, the Enter key has a code of 13, Escape - 27, Space - 32, Tab - 9, etc.

Let's add to our program the ability to find out the code of any key. To do this, we will process the form's OnKeyPress() event. For this mechanism to work, you must set the form's KeyPreview = True.

Here we display a window with text. The event has a Key variable that stores the character corresponding to the key pressed. Using the Ord() function, we find out the code of this character, and then with the IntToStr() function we convert this number into a string.

Example "more serious" - continued

Let's return to our example. It's time to figure out where the empty rows come from in the ListBox. The point is that they are not completely empty. Yes, visually they are empty, but in fact each of them contains 2 special characters. These are characters with codes 13 and 10 (i.e. line #13#10). In Windows, this sequence of these two non-visual characters means the end of the current line and the beginning of a new line. Those. In any file and anywhere in general, line breaks are two characters. And the entire text, accordingly, remains a continuous sequence of characters. These characters can (and even should) be used in cases where you need to insert a line break.

Let's take our word search program to its logical conclusion. So, to get rid of empty lines, we need to remove characters #13 and #10 from the text. This can be done using a loop, similar to how we replaced two commas with one:

while Pos(Chr(13),Text) > 0 do Delete(Text,Pos(Chr(13),Text),1); while Pos(Chr(10),Text) > 0 do Delete(Text,Pos(Chr(10),Text),1);

Well, now the program is fully functional!

Additional functions for working with strings - StrUtils module

The StrUtils.pas add-on module contains additional functions for working with strings. Among these functions there are many useful ones. Here short description frequently used functions:

PosEx(substring, line, indent) - a function similar to the Pos() function, but searching from a specified position (i.e. indented from the beginning of the line). For example, if you want to find the second space in a string, and not the first, you cannot do without this function. To search for the second space manually, you must first cut part of the original string.

AnsiReplaceStr, AnsiReplaceText(string, text_1, text_2) - functions replace string string text_1 with text_2 in the string. The functions differ only in that the first one carries out replacement taking into account the case of characters, and the second - without it.

In our program, we can use these functions to cut characters #13 and #10 from a string by specifying an empty string as the replacement text. Here's a solution in one line of code:

Text:=AnsiReplaceText(AnsiReplaceText(Text,Chr(13),""),Chr(10),"");

DupeString(string, number_of_repetitions) - forms a string consisting of the string string by repeating it a specified number of times.

ReverseString(string) - inverts the string ("123" -> "321").

Also worth mentioning are the register conversion functions.

UpperCase(string) - converts the string to uppercase; LowerCase(string) - Converts a string to lower case.

To convert individual characters, you should use the same functions.

Detailed information about each function can be obtained by entering its name anywhere in the code editor, placing the cursor on this name (or highlighting it) and pressing F1.

Screenshots of the programs described in the article

Conclusion

It was a long lesson. So, today we got acquainted with strings and characters and learned how to work with them. The techniques studied are used almost everywhere. Don't be afraid to experiment - improve your programming skills on your own!

Symbol

A symbol is one sign. Any – letter, number, arithmetic sign or space, punctuation or underscore... And also Special symbols– new line, BackSpace, dollar sign or percent. The "character" type in Delphi is denoted by Char:

ShowMessage("You entered " + c);

ShowMessage("Move to new" + c + "line");

We have already said that symbols are taken from the symbol table ANSI or UNICODE. Most symbols are used, some symbols are auxiliary. Please note that the capital letter "A" and the small letter "a" are different symbols! Also, the Latin “s” and the Russian “s” are different symbols, although they are as similar as two peas in a pod.

The null character is not used, it is reserved as complete zero. Programmers have found a worthy use for this character, using it in text input events when they need to prevent the user from entering any characters. We cannot see service characters in text field. Service symbols are , <Enter>, <Tab> and others. Each character is processed by the computer as a number from 0 to 255, thus word"HELLO" in the machine's memory will look like a set of numbers: "207 208 200 194 197 210".

Symbol Functions

In practice, it is often necessary to process individual characters. Variables of the character type Char can be assigned values ​​in the following way:

Since for a computer a symbol is a number, symbolic data can be compared with each other. In this case, the largest symbol will be the one whose number in the symbol table is greater. For example, "i" will be greater than "a":

if b > c then ShowMessage("True!")

else ShowMessage("False!");

When working with character variables, the Chr() and Ord() functions are often used. Function Chr() takes a number as a parameter, and returns the character that matches that number in the table ANSI:

function Chr (X: Byte): Char;

Function Ord() does the exact opposite, it takes a character as a parameter, and returns the number under which this character is stored in the table ANSI:

function Ord (C: Char): Byte;

Character variables can be used with these functions:

In the first line, in the variable a we wrote the symbol “AND”, which corresponds to the number 200 in the symbol table. In the second, integer variable, we wrote the number 200, since the symbol with this number was written in the variable a, which we passed as a parameter . Finally, in the third line we wrote the number 102 into the whole variable; this number corresponds to the symbol “f”.


Line

A string is a set of characters. A string can be represented as a static or dynamic array of character data. We have already looked at string types in " Control structure if, for loop" : AnsiString – a string from ANSI– symbols, and WideString– a string of UNICODE – characters.

The String type is not a separate type; it defaults to AnsiString. However, it can also be reconfigured to WideString, although this is not necessary. So feel free to specify string variables as String:

s:= "This is multiline" + #13 + "string";

As you can see from the example, a string can be composed of several substrings, and even individual characters can be added to it. In the example, we added character number 13, this is the new line character. As a result of executing this code, the ShowMessage() procedure will display a message split into two lines:

This is multiline

ShortString– a short string from ANSI– symbols. Can contain from 0 to 255 characters. Infrequently used. Actually, you can declare a String type with a pre-specified size:

As you can see, the string is declared with a numeric index, almost like array. Actually, character string and there is array character data, and you can handle it the same way. Indexing characters in a line begin with one, that is, index 1 corresponds to the 1st character of the line.

string:= "Hello";

string := "a"; //changed the 5th character of the line

ShowMessage(stroke); //result: string "Private"

This is also a string, and we will have to deal with it in the future. This string works completely differently than String. String represents array characters, the zero element of which contains the number byte, allocated under this line. A variable type PChar– this is not the line itself, but pointer to the beginning of the line, that is variable points to the first character of a string in the computer's memory. Where then PChar stores quantity byte in line?! And nowhere! We have already talked about the symbol table ANSI, and found out that the null character is empty. Here's the last character PChar it is precisely this symbol that stores, and computer, having found it, considers that the line is over.

With strings PChar it is very inconvenient to work with, but we will have to do this when we work with WinAPI functions directly. WinAPI functions are functions of the Windows, not Delphi. However, Delphi allows you to use them. Sometimes this is necessary, for example, when Delphi tools are not enough to complete the intended task. Using such functions is not always convenient, but they are executed by the processor much faster, since they are contained in the operating system. Example – function MessageBox().

Are you already used to displaying messages using Delphi's ShowMessage() function? Get used to the new feature!

Application.MessageBox("line 1", "line 2",[ buttons + window_type]);

· line 1 - displays text inside the window.

· line 2 – text in the window title.

If you do not specify [buttons + window_type], then a simple window with an OK button will appear, as in the ShowMessage() function.

Ministry of Education and Science of the Russian Federation

Federal Agency for Education

Saratov State Technical University

Balakovo Institute of Engineering, Technology and Management

Working with characters and strings in the C programming language

Guidelines for performing laboratory work in the course “Logic Programming” for full-time students of specialty 071900

Approved

editorial and publishing council

Balakovo Institute of Technology,

technology and management

Balakovo 2009

GOAL OF THE WORK: get acquainted with the concepts of a character, string variable, string constant, pointer to strings, learn how to perform input/output operations on strings, determine the specifics of working with string functions.

1. General concepts

This work discusses character variables, string variables and constants, string input/output operations, and basic functions for working with strings.

1.1. Character variables

Any text consists of symbols. The data type is designed to store one character char. Type variable char can be considered in two ways:

    as an integer that occupies 1 byte and can take values:

    • from 0 to 255 (type unsigned char);

      -128 to 127 (type signed char);

    as one text character.

The same type char may be either signed or unsigned, depending on the operating system and compiler. Therefore use type char is not recommended, it is better to explicitly indicate whether it will be signed ( signed) or unsigned ( unsigned).

Like integers, data type char You can add, subtract, multiply, divide, or you can display it on the screen as one character.

If you want to output the numeric value of a character, also called the ASCII code, then the character value must be converted to type int. For example:

#include

using namespace std;

unsigned char c="A"; // char constants are enclosed in single quotes

cout<

c=126; // char can also be assigned a numeric value

cout<

In this example variable With type char is assigned the value equal to the character "A" (char constants are written as characters in single quotes), then the value is printed to the screen c as a character and its ASCII code, then a variable c the value 126 is assigned, that is, the character with ASCII code 126, and the character and its ASCII code are again displayed on the screen.

1.2. String variables and constants

A text string can be represented as an array of characters like char, but in the SI language a more convenient type was created for storing text strings string.

String variables are used to store a sequence of characters.

String variables must be declared before they can be used. A string variable declaration looks like this: char s,

where s is treated as a character array that can contain up to 14 elements. Suppose s is assigned a string constant:

I AM A COMPUTER PROGRAMMER!

String constant is a sequence of characters enclosed in quotation marks. Each character of a string is stored as an element of an array. The string is stored in memory as follows:

The '\0' null character is automatically added to the system's internal representation of a string so that the program can determine the end of the string. Therefore, when declaring a string variable, you should provide one additional element for the terminating null character.

Strings can also be written into memory and read using character pointers. A character pointer to a string is declared as follows: char*pstr = HELLO

Where pstr it is a pointer that is initialized with a reference to a string constant. A pointer can be changed to point to some other address, but the row that the pointer originally pointed to may no longer be accessible.

Important Notes

Immutability

In JavaScript, strings are immutable, also called "immutable". This means that no matter what functions you apply to them, they do not perform in-place replacement (that is, they do not change the string itself). Any string functions applied to strings return new line. This is also true when we are accessing a specific character in a string.

Const str = "hello"; str.toUpperCase(); // HELLO console.log(str); // hello str.toUpperCase(); // H console.log(str); // hello str = "W"; console.log(str); // hello

Lexicographic order

Lexicographical order is, in other words, alphabetical order. This order is used in dictionaries, telephone directories, notebooks, and so on.

In JavaScript you can compare strings using > and< , и сравнение будет происходить именно лексикографически.

Remember, "8" is not a number, but a string.

Interpolation

In addition to single "" and double quotes "", modern JavaScript contains backticks:

``

With reverse ticks you can use interpolation, instead of concatenation. Here, look:

Const name = "Alex"; const a = 10; const b = 12; console.log(`His name was $(name) and his age was $(a + b)`);

This code will display His name was Alex and his age was 22. You can put any expression inside $().

Interpolation is preferable to concatenation. We advise against using concatenation at all. Here are some of the reasons:

  • This code makes you think more because syntactically + is more like addition.
  • Due to weak typing, you can easily get the wrong result. Concatenation can cause errors.
  • When using concatenation, it is impossible to parse complex strings in your head and understand how they are structured.

Lesson summary

  • A string is a sequence of characters
  • An empty string is also a string (a sequence of zero characters)
  • Denoted by single or double quotes

Creating a string with a constant:

Const str1 = "Hello"; const str2 = "Hello";

It is possible to include a quote of one type inside a string, surrounding it with quotes of another type:

Const str1 = "They call him "Harry", and he likes it"; const str2 = "They call him "Harry", and he likes it";

If the string uses quotes of the same type, they must be shielded using backslash \ :

Const str1 = "They call her \"Ann\", and she likes it"; const str2 = "They call her \"Ann\", and she likes it";

If a string includes a backslash (precisely as a character that you want to have in the string), it must be escaped with another backslash:

Const str = "This is a backslash \\ here" // This is a backslash \ here

There are also control characters- special combinations that generate invisible parts:

Const str = "There is a tab \t and here \ncomes the new line!" // Here is a tab and here // comes the new line!

\t is a tab, \n is a new line. More about shielding (English).

String concatenation

Lines can be stuck together. This process is called concatenation and is specified by the + symbol:

Const name = "Alex"; const age = 22; console.log("His name is " + name + " and his age is " + age); // His name is Alex and his age is 22

The lines will be concatenated in the order in which they are specified: "mos" + "cow" → "moscow" , and "cow" + "mos" → "cowmos"

Access to individual symbols

str[i] is the i-th character of the string str starting at 0. For example, "hexlet" is h and "hexlet" is x.

Here's a function that takes a string and returns a copy of that string minus every other letter. For example, "hexlet" becomes "hxe".

Const skip = (str) =>< str.length) { result = result + str[i]; i = i + 2; } return result; }

str.length is the length of str , that is, the number of characters. It's just a quantity, so we Not We start counting from 0. For example, "food".length is 4.

Lesson transcript

Remember your first "hello, world" program?

Console.log("Hello, World!");

By now you know that a function call is made here, and the console.log function takes an argument. In this case, the argument is not a number, but a "string". This is what we call pieces of text in programming because they are like a sequence of letters on a string.

Lines are everywhere. I'm reading a script now and the text file is a long string. The website where you watch these videos contains a lot of words - all of them are strings. Google's job is to remember strings - that's the essence of search. Files and folders on your computer are identified by their names, which are also just strings.

Just like we did with numbers, we can create a constant from a string:

Const str = "Hello";

You can use single quotes or double quotes, it doesn’t matter so much, the main thing is that they are the same at the beginning and at the end of the line.

If you need to use real quotes within a string, then use a different character to create it. For example:

Const str = "They call him "Harry", and he likes it"; ///They call him "Harry", and he likes it

Here single quotes are used to formulate or delimit a string and then we have the option of putting double quotes inside. Or vice versa:

Const str = "They call him "Harry", and he likes it"; /// They call him "Harry", and he likes it

Double outside - single inside.

But what if this is not possible, and you need to use the same type of quotes both to formulate the string and inside it. If you try this

Const str = "They call him "Harry", and he likes it";

then you will get an error because your string is broken. The program will break at this point because there is a second closing quote of the same type, and then there is a strange word that means nothing, and then a new line. This is incorrect JavaScript.

We need to explain to the JavaScript interpreter that it should interpret some quotes differently. They should not mean "beginning of line" or "end of line", they should mean "quote character".

This is called "shielding". Add an escape character, a backslash \, before the character, and the character is "isolated" from its specific role and becomes a regular character in the string.

Const str = "They call him \"Harry\", and he likes it"; const str2 = "They call her \"Ann\", and she likes it"; // They call him "Harry", and he likes it // They call her "Ann", and she likes it

This escape character can be used to insert other special characters into a string.

There are three points here.

First: if we need a backslash in a string, then it must be escaped with another backslash.

Second: the backslash-t is not an "escaped t-character": you don't need to escape "t", "t" is not a special character; the entire backslash-t design is special control sequence- it is a single tab, essentially a long space.

Third, the backslash-n is another escape sequence that represents a newline. Think of yourself as pressing the Enter key when you type. Therefore, everything that follows will move to a new line.

Now let's try to write a function. It will accept a string - a name and return another string - a greeting. Here's how it should work:

Const result = greet("Sherlock"); // "Well hello, Sherlock"

This function must be able to somehow take an incoming string and concatenate it with another string. This process is called "concatenation" and in JavaScript it is implemented with a plus sign, as when adding numbers:

Const greet = (str) => ( return "Well hello, " + str; )

Now another example. This function takes a string and returns the same string but without every other letter. For example, "California" becomes "Clfri".

Const skip = (str) => ( let i = 0; let result = ""; while (i< str.length) { result = result + str[i]; i = i + 2; } return result; }

These square brackets allow us to get individual characters from a string. As with many processes in programming, you start at 0, not 1. So the first character of str is str , the second is str , and so on. This number is called the "index".

The skip function takes an argument, creates two variables - i for the counter and result for the total string. The count is 0 because we need to start from the first character, and result is an empty string - we will add characters to it one by one.

This is followed by a while loop, with the condition that "i is less than the length of the string." Length means "how many characters". The length of the string "cats" is 4 - it contains 4 characters, 4 letters.

As long as the counter is less than the length, we concatenate or concatenate the resulting string with the character at index i. Then add 2 to the counter. Two, not one, because we need to skip one character.

At some point, the counter will become large enough for the loop condition to become false, and the function will return result .

Let's try calling the function with the "cats" argument:

Const skipped = skip("cats");

The length of "cats" is 4. Even though the indices start at 0, the length is a real number. "c" is not 0 letters, it is one letter. Therefore, the length of "cats" is 4, but the index of its last letter is 3.

  1. 0 is less than four, so enter the while loop
  2. concatenate a string with a character at index 0 - that's "c"
  3. increase the counter by 2
  4. 2 is less than 4, so repeat
  5. to concatenate a string with a character at index 2 is "t". the string has now become "ct"
  6. increase the counter by 2
  7. 4 is not less than 4, so don't repeat it again
  8. return result - "ct"

A test and practical exercise await you.

p»їTrustworthy SEO Agency India Can Increase Revenues of Small Businesses

80% users search on Google and other search engines before making a purchase and more than 50% inquiries generated through search engines get converted. These two statistics prove the importance of Search Engine Optimization. There are many as such stats and facts that make a clear point: any small, mid or large scaled business need professional SEO services. Small businesses and startups often face budget issues. They can take help of any trustworthy SEO agency from India to get the best SEO service in their budget to increase their revenues.
Search holds a great impact on consumers’ minds. According to the various statistics shared by major search engine optimization experts on various authorized websites such as Search Engine Land, Moz, SEO Journal, Digital Marketers India, Hubspot, etc. SEO captures a majority of the leads. Also, the leads coming from the organic search results have a higher conversion rate. These stats and consumer behavior make a clearer point that best SEO service is not a luxury, but a necessity for any business.
To bypass the competition and to increase business growth each organization needs to use the Search Engine Optimization services. The big brands can invest enough money for the expert SEO service offered by a top SEO company or an SEO specialist, but small business owners often compromise on the quality of this service due to less budget. It’s a hard fact the small business and startups end up leaving the opportunities that can be created with the professional SEO service or use a cheap SEO service which yields no positive results.
The small business owners and startups can take benefit of professional SEO services even in the limited budget. The best solution is finding a trustworthy SEO company based out of India. In India, there are many SEO experts who are working with the digital marketing agency and offering best-in-the-industry services. They can provide you the required SEO services in your budget. The wages can be negotiated with an SEO agency India to get better services at lower rates. However, don’t fall for cheap SEO service that charges less and promise to give more as expertise comes at its own cost. You must see the portfolio or ask proper questions before contracting a company for your business.
The SEO experts in India are skilled with the best practices of search engine optimization. Also, there are some SEO specialists in India such as Ash Vyas, who specialize in creating the best search engine optimization strategy for a business in stated budget. The SEO professionals will create a clear plan and will also share what can be the expected results. This way you can be well aware of your investment and returns. This helps in making a better business decision.
A good idea is to find and contract a trustworthy SEO company from India that offers the best SEO services as soonest as possible. You may also start with a small budget and limited activities to start getting your WebPages indexed and boosting your keywords in search engines. Don’t wait for the perfect time or a day when you will have thousands of dollars to invest in the best SEO services. Starting early will help you get quicker results when you can go aggressive with your marketing approach. A trustworthy SEO company based out of India will help you define your current and future plans to yield good results. More indexed pages boosted rankings and credible brand of your business made with continuous professional SEO practices will double inquiries, business, and revenues. Any small business can start with two-digit investment in the professional SEO services. There are many SEO agencies in India that offer low budget yet result from oriented Search Engine Optimization services.

surveys from exile

  • CraigWew

    12.04.2018

    p»їThe Importance of Establishing Rapport With the Customer in Real Estate and General Sales

    The importance of establishing rapport with the customer.
    Establishing rapport with a customer has to be earned and must be approached as a very integral part of the sales process.
    In order to get a customer and yourself to relate on a real one to one basis, involves two things!
    First, you will have to be aware and be there! Second you must understand that there are two different stages that will occur during this process.
    A-Be there-what does that mean?
    o Most people don’t really listen to another person as they talk. Generally they are so busy formulating their next answer or statement that they couldn’t possibly really listen.
    o If this sounds like you, being there means shut up and listen!
    B-What is the first or initial stage?
    o Generally you have just a few minutes to establish yourself in the customers mind as someone they want to deal with.
    o When in doubt it is best to first ask questions that will draw them out and talk about themselves.
    o It is also always safe to appear as a professional-I don’t mean stoic or dry, but someone who knows what they are doing and talks and looks the part.
    C-Other stages
    o As time goes on, through conversation and questions they will have, you will either establish your ability or not.
    o Be aware that they will probably be measuring you for a while. The good news is that at some point, if you have been successful at establishing rapport-they will relax and you can both concentrate on finding or selling the home.
    What else can help me develop rapport?
    o By trying to understand different personality types and then by saying and asking the right questions.
    o If you have good rapport (get on the same wave length as the customer) then the selling is basically over, now it’s just a matter of finding the right home or filling out the listing papers.
    What about different personalities
    o Since this is not a book on psychiatry, for now just understand two main types.
    o There are introverted and extroverted people.
    o You know the type. Think about three people you know that fit each classification.
    What about body language and speech patterns?
    o If they talk fast or slow, try to mimic their speech patterns.
    o If they talk loud or soft, do the same. Are they leaning forward or backward?
    o Needless to say, there are lots of books written on this subject. Just be aware that it is an important factor—especially when you’re sitting in a conference room or at someone’s home discussing a $400,000 deal.
    Developing rapport is a skill that can be learned and improved upon.
    o We all have experienced a salesperson that sold us something and yet we didn’t feel like we were being sold. The reason is he or she, made you feel comfortable to where you trusted them.
    How do we develop rapport?
    o Use your eyes and ears and ask questions. To explain
    o Use the eyes:
    o Look at their dress-their car-their personal possessions and I mean really look at them and decipher what that tells you about them.
    o Use the ears:
    o Listen to what they say and ask questions to get to the bottom of their real MOTIVATION!
    Now during all this conversation, there will probably be one or two things you’ll discover that you have in common with them. (Family, geographical areas, fishing, etc) When you come across common ground, let them know you’re familiarity and then take a minute to discuss it with them.
    What is the Goal?
    o Once they accept you as one of them you're in position to really have a great experience in the sale as you're now working together then as a team—you're no longer the salesman you're now in an advisory position .
    o Remember, the customer either will or will not allow you to enter his world. If you understand this and really work hard to become empathetic with him/her, you can gain a position of trust. In most cases, you will actually see them relax (body language) when this happens you’re on the way.
    o To illustrate this have you ever given a speech and noticed that as you finally connected with an audience member they will nod in approval. These things may all seem trite but they aren’t.
    In closing, if you can earn a customers trust, selling a product or service is much easier and the experience can be enoyable for everyone involved.
    Always remember that a Win/Win is the best situation.