34

--- C# Guide --- Strings

In terms of regular programming, string string data type is one of the most important in C#. This type defines and supports character strings. In a number of other programming languages, a string is an array of characters. And in C#, strings are objects. Therefore, the string type is one of the reference types.

Row construction

The easiest way to construct a character string is to use a string literal. For example, in the following line of code, the string reference variable str is assigned a reference to a string literal:

String str = "Example string";

In this case, the variable str is initialized with the character sequence "Example String". An object of type string can also be created from an array of type char. For example:

Char chararray = ("e", "x", "a", "m", "p", "l", "e"); string str = new string(chararray);

Once an object of type string has been created, it can be used anywhere a string of quoted text is required.

String persistence

Oddly enough, the contents of an object of type string cannot be modified. This means that once a character sequence has been created, it cannot be changed. But this limitation contributes to a more efficient implementation of character strings. Therefore, this, at first glance, an obvious disadvantage actually turns into an advantage. Thus, if a string is required as a variation of an already existing string, then for this purpose a new string should be created containing all the necessary changes. And since unused string objects are automatically collected in "garbage", then you don't even have to worry about the fate of unnecessary strings.

However, it should be emphasized that string reference variables (that is, objects of type string) are subject to change, and therefore they can refer to another object. But the content of the string object itself does not change after it has been created.

Consider an example:

Static void addNewString() ( string s = "This is my stroke"; s = "This is new stroke"; )

Let's compile the application and load the resulting assembly into the ildasm.exe utility. The figure shows the CIL code that will be generated for the void addNewString() method:

Notice the multiple calls to the opcode ldstr (string load). This ldstr opcode in CIL causes a new string object to be loaded onto the managed heap. As a result, the previous object that contained the value "This is my stroke" will eventually be garbage collected.

Working with strings

In class System.String a set of methods is provided for determining the length of character data, searching for a substring in the current string, converting characters from upper case to the bottom and vice versa, etc. We'll look at this class in more detail next.

Field, indexer and property of the String class

The String class has a single field defined:

Public static readonly string Empty;

The Empty field denotes an empty string, i.e. a string that does not contain characters. This is different from an empty String reference, which is simply made to a non-existent object.

In addition, the String class defines a single read-only indexer:

Public char this ( get; )

This indexer allows you to get the character at the specified index. String indexing, like arrays, starts from zero. String objects are persistent and do not change, so it makes sense that the String class supports a read-only indexer.

Finally, the String class defines a single read-only property:

Public int Length ( get; )

The Length property returns the number of characters in a string. The example below shows the use of an indexer and the Length property:

Using System; class Example ( static void Main() ( string str = "Simple string"; // Get string length and 6th character in string using indexer Console.WriteLine("String length is (0), 6th character is "(1)"" , str.Length, str); ) )

String Class Operators

The String class overloads the following two operators: == and !=. The == operator is used to test two character strings for equality. When the == operator is applied to object references, it usually checks to see if both references are to the same object. And when the == operator is applied to object references of type String, the contents of the strings themselves are compared for equality. The same applies to the != operator. When it is applied to object references of type String, the contents of the strings themselves are compared for inequality. At the same time, other relational operators, including =, compare references to objects of type String in the same way as to objects of other types. And to check if one string is greater than another, you should call the Compare() method defined in the String class.

As will become clear later, many kinds of character string comparisons use cultural information. But this does not apply to the == and != operators. After all, they simply compare the ordinal values ​​of characters in strings. (In other words, they compare binary character values ​​that have not been modified by cultural norms, ie, locales.) Therefore, these operators perform string comparisons in a case-insensitive and culture-insensitive manner.

String class methods

The following table lists some of the more interesting methods of this class, grouped by purpose:

String Methods
Method Structure and overloaded versions Purpose
String comparison
Compare() public static int Compare(string strA, string strB)

Public static int Compare(string strA, string strB, bool ignoreCase)

Public static int Compare(string strA, string strB, StringComparison comparisonType)

Public static int Compare(string strA, string strB, bool ignoreCase, CultureInfo culture)

Static method, compares the string strA with the string strB. Returns positive if strA is greater than strB; negative if strA is less than strB; and zero if the strings strA and strB are equal. The comparison is case-sensitive and culturally sensitive.

If the ignoreCase parameter takes boolean true, the comparison does not take into account differences between uppercase and lowercase letters. Otherwise, these differences are taken into account.

The comparisonType parameter specifies the specific way in which strings are compared. The CultureInfo class is defined in the System.Globalization namespace.

public static int Compare(string strA, int indexA, string strB, int indexB, int length)

Public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase)

Public static int Compare(string strA, int indexA, string strB, int indexB, int length, StringComparison comparisonType)

Public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase, CultureInfo culture)

Compares parts of the strings strA and strB. The comparison starts with the string elements strA and strB and includes the number of characters specified by the length parameter. The method returns a positive value if part of strA is greater than part of strB; a negative value if part of strA is less than part of strB; and zero if the compared parts of the strings strA and strB are equal. The comparison is case-sensitive and culturally sensitive.

compareOrdinal() public static int CompareOrdinal(string strA, string strB)

Public static int CompareOrdinal(string strA, int indexA, string strB, int indexB, int count)

Does the same as the Compare() method, but without regard to local settings

CompareTo() public int CompareTo(object value)

Compares the calling string to the string representation of the value object. Returns a positive value if the calling string is greater than the string value; a negative value if the calling string is less than the value string; and zero if the compared strings are equal

public int CompareTo(string strB)

Compares the calling string with strB

Equals() public override bool Equals(object obj)

Returns the boolean true if the calling string contains the same sequence of characters as the string representation of obj. Performs an ordinal comparison, case-sensitive, but culturally insensitive

public bool Equals(string value)

Public bool Equals(string value, StringComparison comparisonType)

Returns the boolean value true if the calling string contains the same sequence of characters as the string value. An ordinal comparison is performed, case-sensitive, but culturally insensitive. The comparisonType parameter defines a specific way to compare strings

public static bool Equals(string a, string b)

Public static bool Equals(string a, string b, StringComparison comparisonType)

Returns boolean true if string a contains the same sequence of characters as string b . An ordinal comparison is performed, case-sensitive, but culturally insensitive. The comparisonType parameter defines a specific way to compare strings

Concatenation (connection) of strings
Concat() public static string Concat(string str0, string str1);

public static string Concat(params string values);

Combines separate string instances into a single string (concatenation)
Search in a string
Contains() public bool Contains(string value) A method that allows you to determine if a string contains a specific substring (value)
StartsWith() public bool StartsWith(string value)

Public bool StartsWith(string value, StringComparison comparisonType)

Returns the boolean true if the calling string starts with the value substring. Otherwise, the boolean value false is returned. The comparisonType parameter specifies how the search is to be performed.

EndsWith() public bool EndsWith(string value)

Public bool EndsWith(string value, StringComparison comparisonType)

Returns the boolean true if the calling string ends with the value substring. Otherwise, it returns the boolean value false. The comparisonType parameter defines a specific search method

IndexOf() public int IndexOf(char value)

Public int IndexOf(string value)

Finds the first occurrence of a given substring or character in a string. If the character or substring you are looking for is not found, then -1 is returned.

public int IndexOf(char value, int startIndex)

Public int IndexOf(string value, int startIndex)

Public int IndexOf(char value, int startIndex, int count)

Public int IndexOf(string value, int startIndex, int count)

Returns the index of the first occurrence of the character or substring value in the calling string. The search starts at the element specified at index startIndex and spans the number of elements specified by the count parameter (if specified). The method returns -1 if the searched character or substring is not found

LastIndexOf() Overloaded versions are similar to the IndexOf() method

Same as IndexOf, but finds the last occurrence of a character or substring instead of the first

IndexOfAny() public int IndexOfAny(char anyOf)

Public int IndexOfAny(char anyOf, int startIndex)

Public int IndexOfAny(char anyOf, int startIndex, int count)

Returns the index of the first occurrence of any character in the anyOf array found in the calling string. The search starts at the element specified by index startIndex and spans the number of elements specified by the count parameter (if any). The method returns -1 if no match is found for any of the characters in the anyOf array. The search is carried out in an ordinal way

LastIndexOfAny Overloaded versions are similar to the IndexOfAny() method

Returns the index of the last occurrence of any character in the anyOf array found in the calling string

Splitting and concatenating strings
Split public string Split(params char separator)

Public string Split(params char separator, int count)

A method that returns a string array with substrings present in this instance, separated from each other by elements from the specified char or string array.

The first form of the Split() method splits the calling string into its component parts. The result is an array containing the substrings retrieved from the calling string. The characters that delimit these substrings are passed in the separator array. If the separator array is empty or refers to an empty string, then a space is used as the substring separator. And in the second form this method returns the number of substrings specified by the count parameter.

public string Split(params char separator, StringSplitOptions options)

Public string Split(string separator, StringSplitOptions options)

Public string Split(params char separator, int count, StringSplitOptions options)

Public string Split(string separator, int count, StringSplitOptions options)

The first two forms of the Split() method split the calling string into parts and return an array containing the substrings obtained from the calling string. The characters that separate these substrings are passed in the separator array. If the separator array is empty, then a space is used as the separator. And in the third and fourth forms of this method, the number of rows is returned, limited by the count parameter.

But in all forms, the options parameter specifies a specific way to handle empty strings, which are generated when two delimiters are adjacent. The StringSplitOptions enumeration defines only two values: None and RemoveEmptyEntries. If the options parameter is None, then empty strings are included in the final result of the split. original string. And if the options parameter is set to RemoveEmptyEntries, then empty strings are excluded from the final result of splitting the original string.

Join() public static string Join(string separator, string value)

Public static string Join(string separator, string value, int startIndex, int count)

Constructs a new string by combining the contents of an array of strings.

The first form of the Join() method returns a string consisting of concatenated substrings passed in the value array. The second form also returns a string consisting of the substrings passed in the value array, but they are concatenated a certain number of counts, starting at the element of the value array. In both forms, each successive line is separated from the previous line by a separator string specified by the separator parameter.

Filling and trimming lines
trim() public string Trim()

Public string Trim(params char trimChars)

A method that allows you to remove all occurrences of a specified set of characters from the beginning and end of the current string.

The first form of the Trim() method removes leading and trailing spaces from the calling string. And the second form of this method removes the leading and trailing occurrences in the calling string of characters from the trimChars array. Both forms return the resulting string.

PadLeft() public string PadLeft(int totalWidth)

Public string PadLeft(int totalWidth, char paddingChar)

Allows you to pad the string with characters on the left.

The first form of the PadLeft() method introduces spaces on the left side of the calling string so that its total length becomes equal to the value the totalWidth parameter. In the second form of this method, the characters indicated by the paddingChar parameter are entered on the left side of the calling string so that its total length becomes equal to the value of the totalWidth parameter. Both forms return the resulting string. If the value of the totalWidth parameter is less than the length of the calling string, then a copy of the unmodified calling string is returned.

PadRight() Similar to PadLeft()

Allows you to pad the string with characters to the right.

Inserting, deleting, and replacing rows
Insert() public string Insert(int startIndex, string value)

Used to insert one string into another, where value is the string to be inserted into the calling string at index startIndex. The method returns the resulting string.

Remove() public string Remove(int startIndex)

Public string Remove(int startIndex, int count)

Used to remove part of a string. In the first form of the Remove() method, the removal is performed starting at the location specified by index startIndex and continuing to the end of the string. And in the second form of this method, the number of characters specified by the count parameter is removed from the string, starting from the place specified by the startIndex index.

Replace() public string Replace(char oldChar, char newChar)

Public string Replace(string oldValue, string newValue)

Used to replace part of a string. The first form of the Replace() method replaces all occurrences of oldChar in the calling string with newChar. And in the second form of this method, all occurrences of the string oldValue in the calling string are replaced by the string newValue.

Case change
ToUpper() public string ToUpper()

Capitalizes all letters in the calling string.

ToLower() public string ToLower()

Makes all letters in the calling string lowercase.

Getting a substring from a string
Substring() public string Substring(int startIndex)

Public string Substring(int startIndex, int length)

In the first form of the Substring() method, the substring is extracted from the location indicated by the startIndex parameter to the end of the calling string. And in the second form of this method, a substring is extracted, consisting of the number of characters specified by the length parameter, starting from the place indicated by the startIndex parameter.

The following program example uses several of the above methods:

Using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 ( class Program ( static void Main(string args) ( // Compare the first two strings string s1 = "this is a string"; string s2 = "this is text, this is a string"; if (String.CompareOrdinal(s1, s2) != 0) Console.WriteLine("Strings s1 and s2 are not equal"); if (String.Compare(s1, 0, s2, 13, 10, true) == 0) Console.WriteLine("However, they contain same text"); // String concatenation Console.WriteLine(String.Concat("\n" + "One, two ","three, four")); // Search in string // First occurrence of substring if (s2. IndexOf("this") != -1) Console.WriteLine("The word \"this\" was found in the line, it is "+ "at: (0) position", s2.IndexOf("this")); / / Last occurrence of the substring if (s2.LastIndexOf("this") != -1) Console.WriteLine("The last occurrence of \"this\" is " + "at (0) position", s2.LastIndexOf("this" )); // Search from the array of characters char myCh = ("S","x","t"); if (s2.IndexOfAny(myCh) != -1) Console.WriteLine("One of the characters from the array ch "+" found in the current current line at position (0)", s2.IndexOfAny(myCh)); // Determine if the string starts with the given substring if (s2.StartsWith("this is text") == true) Console.WriteLine("Substring found!"); // Determine if the string contains a substring // using the example of determining the user's OS string myOS = Environment.OSVersion.ToString(); if (myOS.Contains("NT 5.1")) Console.WriteLine("Your OS Windows system XP"); else if (myOS.Contains("NT 6.1")) Console.WriteLine("Your operating system Windows 7"); Console.ReadLine(); ) ) )

A bit about string comparison in C#

Of all character string processing operations, it is probably the most frequently performed comparison of one string with another. Before looking at any of the string comparison methods, the following should be emphasized: string comparison can be done in the .NET Framework in two main ways:

    First, the comparison may reflect the customs and norms of a particular cultural environment, which are often cultural settings that take effect when a program is executed. This is standard behavior for some, though not all, comparison methods.

    And secondly, the comparison can be performed regardless of the cultural environment settings only on the ordinal values ​​of the characters that make up the string. Generally speaking, culturally-insensitive comparison of strings uses lexicographic order (and linguistic features) to determine whether one string is greater than, less than, or equal to another string. In an ordinal comparison, strings are simply ordered based on the unmodified value of each character.

Because of the differences in how strings are compared between cultures and ordinal comparisons, and the implications of each such comparison, we strongly recommend that you use best practices currently offered by Microsoft. After all, choosing the wrong way to compare strings can cause the program to work incorrectly when it is operated in an environment different from the one in which it was developed.

Choosing how to compare character strings is a very important decision. As a general rule, and without exception, you should choose a culturally sensitive string comparison if it is for the purpose of displaying the result to the user (for example, to display a series of strings sorted in lexicographical order). But if the strings contain fixed information not meant to be modified for cultural differences, such as a file name, keyword, a website address, or a security-related value, then you should select an ordinal string comparison. Of course, the specifics of the particular application being developed will dictate the choice of an appropriate way to compare character strings.

The String class provides a variety of string comparison methods, which are listed in the table above. The most versatile among them is the Compare() method. It allows you to compare two strings in whole or in part, case-sensitive or case-insensitive, in a way of comparison determined by the type parameter StringComparison, as well as cultural information provided by the type parameter CultureInfo.

Those overloads of the Compare() method that do not contain a parameter of type StringComparison perform a case- and culture-sensitive comparison of character strings. And in those overloaded variants that do not contain a parameter of type CultureInfo, the culture information is determined by the current runtime environment.

The StringComparison type is an enumeration that defines the values ​​shown in the table below. Using these values, you can organize string comparisons that suit your application's needs. Therefore, adding a StringComparison type parameter extends the capabilities of the Compare() method and other comparison methods such as Equals(). It also makes it possible to unambiguously specify how strings are to be compared.

Because of the differences between culturally sensitive string comparisons and ordinal comparisons, it is important to be as precise as possible in this regard.

Values ​​defined in the StringComparison enum
Meaning Description
CurrentCulture String comparison is done using the current culture settings
CurrentCultureIgnoreCase String comparison is performed using the current culture settings, but is case insensitive
InvariantCulture String comparison is done using immutable ones, i.e. universal data about the cultural environment
InvariantCultureIgnoreCase String comparison is done using immutable ones, i.e. universal cultural data and case-insensitive
Ordinal String comparison is performed using the ordinal values ​​of the characters in the string. In this case, the lexicographic order may be violated, and conventions accepted in a particular cultural environment are ignored
OrdinalIgnoreCase String comparison is performed using the ordinal values ​​of the characters in the string, but case insensitive

In either case, the Compare() method returns a negative value if the first string being compared is less than the second; a positive value if the first string being compared is greater than the second; and finally zero if both compared strings are equal. Although the Compare() method returns zero if the strings being compared are equal, it is generally better to use the Equals() method or the == operator to determine if character strings are equal.

The fact is that the Compare() method determines the equality of the compared strings based on their sort order. For example, if strings are compared culturally, both strings may be the same in their sort order, but not essentially equal. By default, string equality is determined in the Equals() method based on character ordinal values ​​and is not culturally sensitive. Therefore, by default, both strings are compared in this method for absolute, character-by-character equality, similar to how it is done in the == operator.

Despite the great versatility of the Compare() method, for a simple ordinal comparison of character strings, it is easier to use the CompareOrdinal() method. Finally, keep in mind that the CompareTo() method only compares strings in a culturally sensitive manner.

The following program demonstrates the use of the Compare(), Equals(), CompareOrdinal() methods, and the == and != operators to compare character strings. Note that the first two examples of comparison clearly demonstrate the differences between culturally sensitive string comparison and English ordinal comparison:

Using System; class Example ( static void Main() ( string str1 = "alpha"; string str2 = "Alpha"; string str3 = "Beta"; string str4 = "alpha"; string str5 = "alpha, beta"; int result; / / First, demonstrate the difference between culture-sensitive string comparison and ordinal comparison result = String.Compare(str1, str2, StringComparison.CurrentCulture); Console.Write("Culture-sensitive string comparison: "); if (result 0 ) Console.WriteLine(str1 + " is greater than " + str2); else Console.WriteLine(str1 + "is " + str2); result = String.Compare(str1, str2, StringComparison.Ordinal); Console.Write("Ordinal comparison lines: "); if (result 0) Console.WriteLine(str1 + " is greater than " + str2); else Console.WriteLine(str1 + "is equal to " + str4); // Use the CompareOrdinal() method result = String.CompareOrdinal( str1, str2); Console.Write("Compare strings using CompareOrdinal():\n"); if (result 0) Console.WriteLine(str1 + " greater than " + str2); else Console.WriteLine(str 1 + "is equal to " + str4); Console.WriteLine(); // Determine string equality using the == operator // This is an ordinal comparison of character strings if (str1 == str4) Console.WriteLine(str1 + " == " + str4); // Detect line inequality using the != operator if(str1 != str3) Console.WriteLine(str1 + " != " + str3); if(str1 != str2) Console.WriteLine(str1 + " != " + str2); Console.WriteLine(); // Perform an ordinal case-insensitive string comparison using the Equals() method if(String.Equals(str1, str2, StringComparison.OrdinalIgnoreCase)) Console.WriteLine("Comparing strings using the Equals() method with the " + "parameter OrdinalIgnoreCase: \n" + str1 + " is equal to " + str2); Console.WriteLine(); // Compare parts of strings if(String.Compare(str2, 0, str5, 0, 3, StringComparison.CurrentCulture) > 0) ( Console.WriteLine("Comparing strings based on the current culture:" + "\n3 first characters of the string " + str2 + " is greater than the first 3 characters of the string " + str5); ) ) )

Running this program produces the following result:

There is no separate data type "string of characters" in C language. Working with strings is implemented by using one-dimensional arrays of the char type, i.e. a character string is a one-dimensional char array terminated by a null byte.

A null byte is a byte, each bit of which is equal to zero, while the character constant ´\0´ (a line terminator, or null terminator) is defined for the null byte. Therefore, if a string must contain k characters, then k+1 elements must be specified in the array description.

For example, char a; - means that the string can contain six characters, and the last byte is reserved for zero.

A string constant is a set of characters enclosed in double quotes. For example:

char S="Working with strings";

There is no need to explicitly specify the character ´\0´ at the end of a string constant.

When working with strings, it is convenient to use pointers, for example:

x = "BSUIR";

x = (i>0)? "positive":(i<0)? "отрицательное":"нулевое";

Recall that two standard functions are commonly used to enter strings:

scanf()- introduces values ​​for string variables with an input specifier %s before the appearance of the first “space” character (the “&” character does not need to be specified before the string data ID);

gets()- entering a line with spaces inside this line is completed by pressing the ENTER key.

Both functions automatically end the string with a null byte.

Lines are output by the printf() or puts() functions up to the first null byte ('\0'):

printf() does not move the cursor after output to the beginning of a new line;

puts() automatically moves the cursor after the output of string information to the beginning of a new line.

For example:

printf(" Enter a string without spaces: \n");

scanf("%s",Str);

puts("Enter a string");

The remaining operations on strings are performed using standard library functions whose prototypes are described in the file string.h. Let's take a look at the most commonly used functions.

int function strlen(char *S) returns the length of the string (the number of characters in the string), ignoring the terminating null byte.

char *S1=”Minsk!\0”, S2=”BSUIR-Hurrah!”;

printf(“ %d, %d .”, strlen(S1), strlen(S2));

The result of this section of the program:

int function strcpy(char *S1, char *S2) - copies the contents of string S2 to string S1.

Function strcat(char *S1, char *S2) - joins the string S2 to the string S1 and places it in the array where the string S1 was, while the string S2 is not changed. The null byte that terminated string S1 is replaced by the first character of string S2.

int function strcmp(char *S1, char *S2) compares the strings S1 and S2 and returns the value<0, если S10 if S1>S2; =0 if strings are equal, i.e. contain the same number of identical characters.

Functions for converting a string S to a number:

Integer: int atoi(char*S);

Long Integer: long atol(char*S);

Real: double atof(char*S);

on error, these functions return 0.

Functions for converting a number V into a string S.

»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 the 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 the 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 offer 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

    »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 really mean 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.

The modern C++ standard defines a class with functions and properties (variables) for organizing work with strings (there are no strings as such in the classical C language, there are only char arrays):

#include

#include

#include

To work with strings, you also need to include a standard namespace:

Using namespace std;

Otherwise, you will have to specify the class descriptor std::string instead of string everywhere.

The following is an example of a program that works with string (does not work in old C-compatible compilers!):

#include #include #include using namespace std; int main() (string s = "Test"; s.insert(1,"!"); cout<< s.c_str() << endl; string *s2 = new string("Hello"); s2->erase(s2->end()); cout<< s2->c_str(); cin.get(); return 0; )

The main features that the string class has:

  • initialization with an array of characters (a built-in string) or another object of type string . The built-in type does not have the second capability;
  • copying one line to another. For a built-in type, you have to use the strcpy() function;
  • access to individual characters of a string for reading and writing. In the built-in array, this is done using the index operation or indirect addressing using a pointer;
  • comparing two strings for equality. For a built-in type, the functions of the strcmp() family are used;
  • concatenation (concatenation) of two strings, giving the result either as a third string, or instead of one of the original ones. For a built-in type, the strcat() function is used, but to get the result in a new line, you need to use the strcpy() and strcat() functions in sequence, and also take care of memory allocation;
  • built-in means for determining the length of a string (member functions of the class size() and l ength()). The only way to find out the length of a built-in type string is by computing it with the strlen() function;
  • the ability to find out if a string is empty.

Let's take a closer look at these basic features.

String initialization when describing and string length(not including the terminating null terminator):

String st("My string\n"); cout<< "Длина " << st << ": " << st.size() << " символов, включая символ новой строки\n";

The string can also be empty:

String st2;

To check whether is the string empty, you can compare its length with 0:

if (!st.size()) // empty

or use the empty() method, which returns true for an empty string and false for a non-empty one:

if (st.empty()) // empty

The third form of string creation initializes an object of type string with another object of the same type:

String st3(st);

The string st3 is initialized with the string st . How can we make sure that these strings match? Let's use the comparison operator (==):

If (st == st3) // initialization succeeded

How copy one line to another? With the usual assignment operator:

st2 = st3; // copy st3 to st2

For string concatenation the addition operator (+) or the addition-assignment operator (+=) is used. Let two lines be given:

String s1("hello, "); string s2("world\n");

We can get a third string consisting of the concatenation of the first two, thus:

String s3 = s1 + s2;

If we want to add s2 to the end of s1 , we have to write:

S1 += s2;

The addition operation can concatenate class objects string not only among themselves, but also with strings of the built-in type. You can rewrite the example above so that special characters and punctuation marks are represented by the built-in type char * , and significant words are represented by objects of class string:

Const char *pc = ", "; string s1("hello"); string s2("world"); string s3 = s1 + pc + s2 + "\n"; cout<< endl << s3;

Such expressions work because the compiler "knows" how to automatically convert objects of the built-in type to objects of class string . It is also possible to simply assign a built-in string to a string object:

String s1; const char *pc = "a character array"; s1=pc; // right

The reverse transformation is does not work. Attempting to perform the following built-in type string initialization will cause a compilation error:

Char*str = s1; // compilation error

To do this conversion, you must explicitly call the member function called c_str() ("C string"):

Const char *str = s1.c_str();

The c_str() function returns a pointer to a character array containing the string of the string object, as it would be in the built-in string type. The const keyword here prevents the "dangerous" possibility in modern visual environments of directly modifying the contents of an object via a pointer.

To individual characters an object of type string , like a built-in type, can be accessed using the index operation. For example, here is a code snippet that replaces all dots with underscores:

String str("www.disney.com"); int size = str.size(); for (int i = 0; i< size; i++) if (str[i] == ".") str[ i ] = "_"; cout << str;

Replace(str.begin(), str.end(), ".", "_");

True, it is not the replace method of the string class that is used here, but the algorithm of the same name:

#include

Since the string object behaves like a container, other algorithms can be applied to it. This allows you to solve problems that are not directly solved by the functions of the string class.

Below is a brief description of the main operators and functions of the string class, links in the table lead to Russian-language descriptions on the Internet. For a more complete list of the capabilities of the string class, see, for example, Wikipedia or cplusplus.com.

Specifying characters in a string

operator=

assigns values ​​to a string

assign

assigns characters to a string

Accessing individual characters

at

getting the specified character with checking for index out of bounds

operator

getting the specified character

front

getting the first character

back

getting the last character

data

returns a pointer to the first character of a string

c_str

returns unmodifiable C character array containing the characters of the string

Checking for string capacity

empty

checks if a string is empty

size
length

returns the number of characters in a string

max_size

returns the maximum number of characters

reserve

reserves storage space

Operations on a string

clear

clears the contents of the string

insert

character insertion

erase

character removal

push_back

adding a character to the end of a string

pop_back

removes the last character

append

operator+=

adds characters to the end of a string

compare

compares two strings

replace

replaces every occurrence of the specified character

substr

returns a substring

copy

copies characters

resize

changes the number of characters stored

Strings. Line input/output. Formatted I/O. String processing using standard C language functions. Working with memory.

1.1. Declaring and initializing strings.

A string is an array of characters that ends with the empty character '\0'. A string is declared as a normal character array, for example,

char s1; // string nine characters long

char*s2; // pointer to string

The difference between pointers s1 and s2 is that pointer s1 is a named constant, while pointer s2 is a variable.

String constants are enclosed in double quotes, unlike characters, which are enclosed in single quotes. For example,

“This is a string.”

The length of a string constant cannot exceed 509 characters according to the standard. However, many implementations allow longer strings.

When initializing strings, it is better not to specify the dimension of the array; the compiler will do this by counting the length of the string and adding one to it. For example,

char s1 = “This is a string.”;

In the C programming language, there are a large number of functions for working with strings, the prototypes of which are described in the header files stdlib.h and string.h. Working with these functions will be discussed in the following paragraphs.

1.2. Line input/output.

To enter a string from the console, use the function

char* gets(char*str);

which writes a string to address str and returns the address of the input string. The function stops input if it encounters the character '\n' or EOF (end of file). The newline character is not copied. A null byte is placed at the end of the read line. On success, the function returns a pointer to the read line, and on failure, NULL.

To output a string to the console, use the standard function

int puts (const char *s);

which returns a non-negative number on success and EOF on failure.

The gets and puts function prototypes are described in the stdio.h header file.

#include

printf("Input String: ");

1.3. Formatted I/O.

For formatted input from the console, use the function

int scanf (const char *format, ...);

which returns the number of data units read on success, and EOF on failure. The format parameter must point to a format string that contains input format specifications. The number and types of arguments that follow after the format string must match the number and types of input formats specified in the format string. If this condition is not met, then the result of the function is unpredictable.

Space, "\t" or "\n" characters in the format string describe one or more empty characters in the input stream, which include the following characters: space, '\t', '\n', '\v', '\f '. The scanf function skips null characters in the input stream.

Literal characters in a format string, with the exception of the % character, require exactly the same characters to appear in the input stream. If there is no such character, scanf stops input. The scanf function skips literal characters.

In general, the input format specification is:

%[*] [width] [modifiers] type

The character '*' denotes a gap when entering a field defined by this specification;

- 'width' defines the maximum number of characters entered by this specification;

The type can take the following values:

c is a character array,

s – character string, strings are separated by empty characters,

d is a signed integer at 10 s/s,

i is a signed integer, the number system is based on the first two digits,

u is an unsigned integer in 10 s/s,

o is an unsigned integer in 8 s/s,

x, X is an unsigned integer in 16 s/s,

e, E, f, g, G - floating number,

p is a pointer to a pointer,

n is a pointer to an integer,

[…] is an array of scanned characters, for example, .

In the latter case, only the characters enclosed in square brackets will be entered from the input stream. If the first character inside square brackets is '^', then only those characters that are not included in the array are entered. The range of characters in an array is specified via the '-' character. When characters are entered, leading blank characters and the terminating null byte of the string are also entered.

Modifiers can take the following values:

h is a short integer,

l, L - long integer or float,

and are only used for integers or floats.

The following example shows use cases for the scanf function. Note that the format specifier is preceded by a space before entering a floating number.

#include

printf("Input an integer: ");

scanf("%d", &n);

printf("Input a double: ");

scanf(" %lf", &d);

printf("Input a char: ");

scanf(" %c", &c);

printf("Input a string: ");

scanf("%s", &s);

Note that in this program the floating point number is initialized. This is done in order for the compiler to include a library to support working with floating numbers. If this is not done, an error will occur at run time when entering a floating number.

For formatted output to the console, use the function

int printf (const char *format, ...);

which returns the number of output units on success and EOF on failure. The format parameter is a format string that contains output format specifications. The number and types of arguments that follow the format string must match the number and types of the output format specifications given in the format string. In general, the output format specification is:

%[flags] [width] [.precision] [modifiers] type

- ‘flags’ are various symbols that specify the output format;

- 'width' defines the minimum number of characters output by this specification;

- ‘.precision’ defines the maximum number of characters to be output;

- ‘modifiers’ specify the type of arguments;

- 'type' specifies the type of the argument.

The following output format is used to print signed integers:

%[-] [+ | space] [width] [l] d

- – alignment to the left, by default – to the right;

+ - the sign '+' is displayed, note that for negative numbers the sign '-' is always displayed;

‘space’ – a space is displayed at the character position;

d is the data type int.

To output unsigned integers, the following output format is used:

%[-] [#] [width] [l]

# - displays initial 0 for numbers in 8 c/c or initial 0x or 0X for numbers in 16 c/c,

l – long data type modifier;

u is an integer in 10c/c,

o is an integer in 8 c/c,

x, X is an integer in 16 c/c.

To display floating point numbers, the following output format is used:

%[-] [+ | space] [width] [.precision]

"precision" refers to the number of digits after the decimal point for the f, e, and E formats, or the number of significant digits for the g and G formats. Numbers are rounded off. The default is six decimal digits of precision;

f is a fixed point number,

e is a number in exponential form, the exponent is denoted by the letter "e",

E is a number in exponential form, the exponent is denoted by the letter "E",

g is the shortest of the f or g formats,

G is the shortest of the f or G formats.

printf ("n = %d\n f = %f\n e = %e\n E = %E\n f = %.2f", -123, 12.34, 12.34, 12.34, 12.34);

// prints: n = 123 f = 12.340000 e = 1.234000e+001 E = 1.234000E+001 f = 12.34

1.4. String formatting.

There are variants of the scanf and printf functions that are designed to format strings and are called sscanf and sprintf, respectively.

int sscanf (const char *str, const char *format, ...);

reads data from the string specified by the str parameter according to the format string specified by the format parameter. Returns the amount of data read on success, EOF on failure. For example,

#include

char str = "a 10 1.2 String No input";

sscanf(str, "%c %d %lf %s", &c, &n, &d, s);

printf("%c\n", c); // prints: a

printf("%d\n", n); // prints: 10

printf("%f\n", d); // prints: 1.200000

printf("%s\n", s); // prints: String

int sprintf (char *buffer, const char *format, ...);

formats the string according to the format specified by the format parameter and writes the result to the buffer character array. The function returns the number of characters written to the buffer character array, excluding the terminating null byte. For example,

#include

char str = "c = %c, n = %d, d = %f, s = %s";

char s = "This is a string.";

sprintf(buffer, str, c, n, d, s);

printf("%s\n", buffer); // prints: c = c, n = 10, d = 1.200000, s = This is a string

1.5. Convert strings to numeric data.

The prototypes of the functions for converting strings to numeric data are given in the stdlib.h header file, which must be included in the program.

To convert a string to an integer, use the function

int atoi (const char *str);

char *str = "-123";

n = atoi(str); // n = -123

To convert a string to a long integer, use the function

long int atol (const char *str);

which, if successful, returns the integer to which the string str was converted, and 0 if unsuccessful. For example,

char *str = "-123";

n = atol(str); // n = -123

To convert a string to a double, use the function

double atof (const char *str);

which, if successful, returns a floating number of type double, into which the string str is converted, and in case of failure, 0. For example,

char *str = "-123.321";

n = atof(str); // n = -123.321

The following functions perform similar actions to atoi, atol, atof, but provide more functionality.

long int strtol (const char *str, char **endptr, int base);

converts the string str to a long int, which it returns. The parameters of this function have the following purpose.

If the base argument is 0, then the conversion depends on the first two characters of str:

If the first character is a digit from 1 to 9, then the number is assumed to be represented in 10 c/c;

If the first character is the number 0 and the second character is a number from 1 to 7, then the number is assumed to be represented in 8 c/c;

If the first character is 0 and the second character is 'X' or 'x', then the number is assumed to be represented in 16 c/c.

If the base argument is a number from 2 to 36, then this value is taken as the base of the number system, and any character that goes beyond this system stops the conversion. Number systems with base 11 to 36 use the symbols 'A' to 'Z' or 'a' to 'z' to represent digits.

The value of the endptr argument is set by the strtol function. This value contains a pointer to the character that stopped the conversion of str. The strtol function returns the converted number on success, and 0 on failure. For example,

n = strtol("12a", &p, 0);

printf(" n = %ld, %stop = %c, n, *p); // n = 12, stop = a

n = strtol("012b", &p, 0);

printf(" n = %ld, %stop = %c, n, *p); // n = 10, stop = b

n = strtol("0x12z", &p, 0);

printf(" n = %ld, %stop = %c, n, *p); // n = 18, stop = z

n = strtol("01117", &p, 0);

printf(" n = %ld, %stop = %c, n, *p); // n = 7, stop = 7

unsigned long int strtol (const char *str, char **endptr, int base);

works similar to the strtol function, but converts the character representation of a number to an unsigned long int.

double strtod (const char *str, char **endptr);

converts the symbolic representation of a number to a double.

All functions listed in this paragraph stop their work when they encounter the first character that does not fit the format of the number in question.

In addition, if the character value of a number exceeds the range of allowable values ​​for the corresponding data type, then the atof, strtol, strtoul, strtod functions set the value of the errno variable to ERANGE. The errno variable and the ERANGE constant are defined in the math.h header file. The atof and strtod functions return HUGE_VAL, the strtol function returns LONG_MAX or LONG_MIN, and the strtoul function returns ULONG_MAX.

The non-standard itoa, ltoa, utoa, ecvt, fcvt, and gcvt functions can be used to convert numeric data to character strings. But it is better to use the standard sprintf function for these purposes.

1.6. Standard functions for working with strings.

In this section, functions for working with strings are considered, the prototypes of which are described in the string.h header file.

1. String comparison. The strcmp and strncmp functions are used to compare strings.

int strcmp (const char *str1, const char *str2);

compares strings str1, str2 lexicographically and returns -1, 0, or 1 if str1 is less than, equal to, or greater than str2, respectively.

int strncmp (const char *str1, const char *str2, size_t n);

lexicographically compares at most the first n characters from the strings str1 and str2. The function returns -1, 0, or 1 if the first n characters of str1 are less than, equal to, or greater than the first n characters of str2, respectively.

// string comparison example

#include

#include

char str1 = "aa bb";

char str2 = "aa aa";

char str3 = "aa bb cc";

printf("%d\n", strcmp(str1, str3)); // prints: -1

printf("%d\n", strcmp(str1, str1)); // prints: -0

printf("%d\n", strcmp(str1, str2)); // prints: 1

printf("%d\n", strncmp(str1, str3, 5)); // prints: 0

2. Copying lines. The strcpy and strncpy functions are used to copy strings.

char *strcpy (char *str1, const char *str2);

copies the string str2 to the string str1. The string str2 is copied in its entirety, including the terminating null byte. The function returns a pointer to str1. If the lines overlap, then the result is unpredictable.

char *strncpy (char *str1, const char *str2, size_t n);

copies n characters from string str2 to string str1. If the string str2 contains less than n characters, then the last null byte is copied as many times as needed to expand the string str2 to n characters. The function returns a pointer to the string str1.

char str2 = "Copy string.";

strcpy(str1, str2);

printf(str1); // prints: Copy string.

4. Connecting strings. The strcat and strncat functions are used to concatenate strings into a single string.

char* strcat (char *str1, const char *str2);

appends the string str2 to the string str1, with the terminating null byte of the string str1 erased. The function returns a pointer to the string str1.

char* strncat (char *str1, const char *str2, size_t n);

concatenates n characters from string str2 to string str1, erasing the terminating null byte of str1. The function returns a pointer to the string str1. if the length of the string str2 is less than n, then only the characters included in the string str2 are appended. After string concatenation, a null byte is always added to str1. The function returns a pointer to the string str1.

#include

#include

char str1 = "string";

char str2 = "catenation";

char str3 = "Yes No";

strcat(str1, str2);

printf("%s\n", str1); // prints: String catenation

strncat(str1, str3, 3);

printf("%s\n", str1); // prints: String catenation Yes

5. Search for a character in a string. The strchr, strrchr, strspn, strcspn, and strpbrk functions are used to search for a character in a string.

char* strchr (const char *str, int c);

searches for the first occurrence of the character specified by parameter c in the string str. On success, the function returns a pointer to the first character found, and on failure, NULL.

char* strrchr (const char *str, int c);

searches for the last occurrence of the character specified by parameter c in the string str. On success, the function returns a pointer to the last found character, and on failure, NULL.

#include

#include

char str = "char search";

printf("%s\n", strchr(str, "r")); // prints: r search

printf("%s\n", strrchr(str, "r")); // prints: rch

size_t strspn (const char *str1, const char *str2);

returns the index of the first character in str1 that is not in str2.

size_t strcspn (const char *str1, const char *str2);

returns the index of the first character in str1 that is in str2.

char str = "123 abc";

printf("n = %d\n", strspn(str, "321"); // prints: n = 3

printf ("n = %d\n", strcspn (str, "cba"); // prints: n = 4

char* strpbrk (const char *str1, const char *str2);

finds the first character in str1 that is equal to one of the characters in str2. On success, the function returns a pointer to that character, and on failure, NULL.

char str = "123 abc";

printf("%s\n", strpbrk(str, "bca")); // prints: abc

6. Comparison of strings. The strstr function is used to compare strings.

char* strstr (const char *str1, const char *str2);

finds the first occurrence of the string str2 (without the trailing null byte) in the string str1. On success, the function returns a pointer to the found substring, and on failure, NULL. If the str1 pointer points to a zero-length string, then the function returns the str1 pointer.

char str = "123 abc 456;

printf("%s\n", strstr(str, "abc"); // print: abc 456

7. Parsing a string into tokens. The strtok function is used to parse a string into tokens.

char* strtok (char *str1, const char *str2);

returns a pointer to the next token (word) in string str1, where token separators are characters from string str2. If the tokens are over, then the function returns NULL. On the first call to the strtok function, the str1 parameter must point to a string that is parsed into tokens, and on subsequent calls, this parameter must be set to NULL. After finding the token, the strtok function writes a null byte after this token in place of the delimiter.

#include

#include

char str = "12 34 ab cd";

p = strtok(str, " ");

printf("%s\n",p); // prints values ​​in a column: 12 34 ab cd

p = strtok(NULL, " ");

8. Determining the length of the string. The strlen function is used to determine the length of a string.

size_t strlen(const char *str);

returns the length of the string, ignoring the last null byte. For example,

char str = "123";

printf("len = %d\n",strlen(str)); // prints: len = 3

1.7. Functions for working with memory.

The string.h header file also describes functions for working with memory blocks, which are similar to the corresponding functions for working with strings.

void* memchr(const void *str, int c, size_t n);

searches for the first occurrence of the character specified by c in n bytes of str.

int memcmp(const void *str1, const void *str2, size_t n);

compares the first n bytes of str1 and str2.

void* memcpy(const void *str1, const void *str2, size_t n);

copies the first n bytes from string str1 to string str2.

void* memmove(const void *str1, const void *str2, size_t n);

copies the first n bytes from str1 to str2, ensuring that overlapping strings are handled correctly.

void* memset(const void *str, int c, size_t n);

copies the character specified by c into the first n bytes of str.