Today I want to review some basics by sharing with you the N implementations of how to delete the last character of a string.
01First type, string method
This type of method is implemented directly through the string type's own methods.
1, Substring method
Most people believe that the first thing that comes to mind may be this method.Substring method is a built-in method of the string, you can specify the starting index position of 0 and the length of the string length minus 1, the specified length of the sub-string directly intercepted, so as to delete the last character purpose.
The sample code is as follows:
public static string StringSubstring(string source)
{
return (0, - 1);
}
2、Range operators
This method is arguably the cleanest method, and it's probably not one that people use a lot. The range operator has been supported since C# 8. It takes the form of, e.g., vary[start..end], which specifies the beginning and end of a certain indexed range as its operands. The left-hand operand is the inclusive beginning of the range. The right operand is the non-inclusive end of the range. Either operand can be an index at the beginning or end of the sequence.
Various ways to express the range of a set are listed below:
The range operator also applies to strings, and the implementation code is as follows:
public static string StringRangeOperator(string source)
{
return source[..^1];
}
3、Remove method
Remove method is a built-in string method to remove all characters from the specified starting index position to the end, so you can set the starting index as the last character, so as to delete the last character purpose.
The sample code is as follows:
public static string StringRemove(string source)
{
return ( - 1);
}
4. Create method
Create method is a static method of the string, this method I believe we use less, its role is to create a new string with a specific length, and after the creation of the specified callback to initialize it. Here we look directly at the implementation of the code:
public static string StringCreate(string source)
{
return ( - 1, source, (span, state) =>
{
for (var i = 0; i < - 1; i++)
{
span[i] = state[i];
}
});
}
The following is a simple explanation of the above code, the first parameter - 1 is to create a target string that is 1 bit less than the length of the original string; the second parameter source is to pass the original string as a parameter to the third parameter; the third parameter is a two-parameter no-return-value delegate, of which the span parameter indicates that the target string corresponds to the Span
5. Summary
The above four methods mainly use the string's own built-in methods for operation, the following four methods we have three groups of comparative performance tests, each group of 100, 1000, 10000 length of the string respectively.
Through the test results, it is not difficult to find that, in addition to the Create method, the other three methods are not very different, and in a comprehensive view, it can be said that Remove is optimal.
02The second type, StringBuilder method
If you need to operate on a large number of strings, I believe we will immediately think of using StringBuilder to optimize performance, the following is a brief introduction to the use of two StringBuilder way to delete the last character of the string.
1. Append method
String is equivalent to an array of characters, so we can loop through the string, and then use StringBuilder's Append method to splice, the implementation code is as follows:
public static string StringBuilderAppend(string source)
{
var sb = new StringBuilder();
for (var i = 0; i < - 1; i++)
{
(source[i]);
}
return ();
}
2、Length way
I believe we should be more puzzled to see this title, what does this mean, we first look at the code and then explain:
public static string StringBuilderLength(string source)
{
var sb = new StringBuilder(source);
--;
return ();
}
First of all, the first line of code indicates that the original string to create a variable string; focus on the second line, directly on the StringBuilder length of the implementation of the minus 1 operation; and finally the StringBuilder into a string to return.
First of all, StringBuilder's Length attribute indicates the number of characters contained in the current variable string, when the operation is performed on it, it is equivalent to telling the StringBuilder object to ignore the last character, and not really deleting any characters within it, the ignored characters are still contained within the StringBuilder object, only that they are no longer regarded as part of the string. The ignored character is still contained within the StringBuilder object, but it is no longer considered part of the string, so the string returned is the one we want when we call the .
3. Summary
In the following, we perform three sets of comparative performance tests for the two methods, each with strings of lengths 100, 1000, and 10000, respectively.
It is easy to see from this set of test results that the direct manipulation of the Length attribute significantly outperforms the Append method, but is not quite as good as the direct string manipulation.
03Category III, Array approach
Above we mentioned that strings are equivalent to arrays of characters, so we can directly use the methods corresponding to arrays.
1. For method
We can directly build a target character array, and then copy the corresponding characters in the original string to the new character array, and finally the new character array into a string to return, the code is as follows:
public static string ArrayFor(string source)
{
var chars = new char[ - 1];
for (var i = 0; i < ; i++)
{
chars[i] = source[i];
}
return new string(chars);
}
2、Resize method
This method you may use less, it can change the number of array elements to the specified size. The idea is a bit like the above StringBuilder object directly modify the Length property. Here is a direct look at the code:
public static string ArrayResize(string source)
{
var chars = ();
(ref chars, - 1);
return new string(chars);
}
3. CopyTo method
I believe that this method should be a little bit of influence, we have also mentioned in the previous article. Simply put, the original array is copied to the target array, the code is as follows:
public static string ArrayCopyTo(string source)
{
var chars = new char[ - 1];
(0, chars, 0, );
return new string(chars);
}
4、String way
String way is the value when the original string is converted to an array of characters, directly use the String constructor to get the result we want by starting from the specified position in the character array and specifying the length. The code is as follows:
public static string ArrayString(string source)
{
var chars = ();
return new string(chars, 0, - 1);
}
Where the first parameter of the string constructor represents the character array, the second parameter represents the 0th index from the character array, and the third parameter represents the number of elements taken from the character array.
5. Summary
The same four methods above are tested for performance in three sets of comparisons, each of which is a string of length 100, 1000, and 10000, respectively.
It is not difficult to find through the test results, the CopyTo method and the String way is relatively good, than the StringBuilder way is a little better.
04Category IV, Linq approach
The core idea of the Linq approach is to get the character array corresponding to the target string through the Linq method and then convert it to a string for return.
1. Take method
The main function of the Take method is to return a specified number of consecutive elements from the beginning of the sequence, so the code is implemented as follows:
public static string LinqTake(string source)
{
return new string(( - 1).ToArray());
}
2. SkipLast method
The SkipLast method, which has been around since C# 8, returns all the elements of a collection except the last specified number of elements.
public static string LinqSkipLast(string source)
{
return new string((1).ToArray());
}
3、Range + Select method
Range method I believe we use less, its role is to generate a specified range of integer sequences. We first look at the code and then explain:
public static string LinqRange(string source)
{
return new string((0, - 1).Select(i => source[i]).ToArray());
}
Here the Range method is equivalent to generating a sequence of target string indexes, i.e. [0.. - 1], and then through the Seletc method to take the corresponding characters of the original string, and finally get the result.
4. Summary
Again three sets of comparative performance tests are performed for the above three methods, each set of strings of lengths 100, 1000, and 10000, respectively.
It is not difficult to find through the test results, Range + Select method is relatively good, but than the previous types of methods is far from it.
05Fifth category, Linq + String combination approach
This type of method is implemented through a combination of Linq methods and string methods.
1. Concat method
Concat method is a string of static methods can be connected to multiple characters into a new string, and then through the Linq SkipLast method with our purpose, the code is as follows:
public static string LinqStringConcat(string source)
{
return ((1));
}
2. Join method
Join method is also a static method of the string, the main role is to use the specified separator to connect the members of the collection. Therefore, you can also achieve a similar effect Concat.
public static string LinqStringJoin(string source)
{
return ("", (1));
}
3. Summary
In the following, we perform three sets of comparative performance tests for the two methods, each with strings of lengths 100, 1000, and 10000, respectively.
The results of this set of tests show that the difference between the two is not much, and it is worse compared to the previous method.
06Category VI. Data view approach
The core idea of the data view approach is implemented through Span, Memory and ArraySegment.
1. AsSpan method
Span
public static string Span(string source)
{
var span = (0, - 1);
return new string(span);
}
2. AsMemory method
Memory
public static string Memory(string source)
{
var memory = (0, - 1);
return new string();
}
3. ArraySegment method
ArraySegment
public static string ArraySegment(string source)
{
var segment = new ArraySegment<char>((), 0, - 1);
return new string(, , );
}
4. Summary
Again three sets of comparative performance tests are performed for the above three methods, each set of strings of lengths 100, 1000, and 10000, respectively.
Through the test results can be found, three methods are quite high performance, of course, which ArraySegment method is relatively worse. President of the data view method has been and the first type of string method is not comparable.
07Category VII. Regular expression approach
Two methods of regular expression implementation are explained here.
1. Replace method
The Replace method is a static method of Regex with the following code:
public static string RegexReplace(string source)
{
return (source, ".$", "");
}
2. Match method
The Match method is also a static method of Regex with the following code:
public static string RegexMatch(string source)
{
var match = (source, @"^(.*).$");
return [1].Value;
}
3. Summary
In the following, we perform three sets of comparative performance tests for the two methods, each with strings of lengths 100, 1000, and 10000, respectively.
The results of this set of tests show that there is not much difference between the two, and the difference in performance relative to the previous method is centered.
From a holistic point of view, the use of the first type of string method with high performance and concise code is the most preferred, and the main purpose of listing so many ways to familiarize themselves with some of the basic methods, although in this case is not the optimal solution, but it may be used in other places just right.
We all know that there may be many ways to do the same event, and then you can choose an optimal method, but this presupposes that you know what these methods are so that you can have a choice.
classifier for sums of money: The test method code as well as the sample source code have been uploaded to the code repository for those who are interested./hugogoos/Planner