[英]How to get the last five characters of a string using Substring() in C#?
I can get the first three characters with the function below.我可以使用下面的函数获取前三个字符。
However, how can I get the output of the last five characters ("Three") with the Substring()
function?但是,如何使用
Substring()
函数获取最后五个字符(“三个”)的输出? Or will another string function have to be used?还是必须使用另一个字符串函数?
static void Main()
{
string input = "OneTwoThree";
// Get first three characters
string sub = input.Substring(0, 3);
Console.WriteLine("Substring: {0}", sub); // Output One.
}
If your input string could be less than five characters long then you should be aware that string.Substring
will throw an ArgumentOutOfRangeException
if the startIndex
argument is negative.如果您的输入字符串长度可能少于五个字符,那么您应该知道如果
startIndex
参数为负,则string.Substring
将抛出ArgumentOutOfRangeException
。
To solve this potential problem you can use the following code:要解决此潜在问题,您可以使用以下代码:
string sub = input.Substring(Math.Max(0, input.Length - 5));
Or more explicitly:或更明确地说:
public static string Right(string input, int length)
{
if (length >= input.Length)
{
return input;
}
else
{
return input.Substring(input.Length - length);
}
}
string sub = input.Substring(input.Length - 5);
If you can use extension methods, this will do it in a safe way regardless of string length:如果您可以使用扩展方法,无论字符串长度如何,这都会以安全的方式进行:
public static string Right(this string text, int maxLength)
{
if (string.IsNullOrEmpty(text) || maxLength <= 0)
{
return string.Empty;
}
if (maxLength < text.Length)
{
return text.Substring(text.Length - maxLength);
}
return text;
}
And to use it:并使用它:
string sub = input.Right(5);
static void Main()
{
string input = "OneTwoThree";
//Get last 5 characters
string sub = input.Substring(6);
Console.WriteLine("Substring: {0}", sub); // Output Three.
}
Substring(0, 3)
- Returns substring of first 3 chars. Substring(0, 3)
- 返回前 3 个字符的子字符串。 //One
Substring(3, 3)
- Returns substring of second 3 chars. Substring(3, 3)
- 返回第二个 3 个字符的子字符串。 //Two
Substring(6)
- Returns substring of all chars after first 6. //Three
Substring(6)
- 返回前 6 个字符之后的所有字符的子字符串。// //Three
一种方法是使用字符串的Length
属性作为Substring
输入的一部分:
string sub = input.Substring(input.Length - 5); // Retrieves the last 5 characters of input
Here is a quick extension method you can use that mimics PHP syntax.这是您可以使用的模拟 PHP 语法的快速扩展方法。 Include
AssemblyName.Extensions
to the code file you are using the extension in.将
AssemblyName.Extensions
包含到您正在使用扩展名的代码文件中。
Then you could call:然后你可以调用:
input.SubstringReverse(-5) and it will return "Three".
namespace AssemblyName.Extensions {
public static class StringExtensions
{
/// <summary>
/// Takes a negative integer - counts back from the end of the string.
/// </summary>
/// <param name="str"></param>
/// <param name="length"></param>
public static string SubstringReverse(this string str, int length)
{
if (length > 0)
{
throw new ArgumentOutOfRangeException("Length must be less than zero.");
}
if (str.Length < Math.Abs(length))
{
throw new ArgumentOutOfRangeException("Length cannot be greater than the length of the string.");
}
return str.Substring((str.Length + length), Math.Abs(length));
}
}
}
Substring.子串。 This method extracts strings.
此方法提取字符串。 It requires the location of the substring (a start index, a length).
它需要子字符串的位置(起始索引、长度)。 It then returns a new string with the characters in that range.
然后它返回一个包含该范围内字符的新字符串。
See a small example :看一个小例子:
string input = "OneTwoThree";
// Get first three characters.
string sub = input.Substring(0, 3);
Console.WriteLine("Substring: {0}", sub);
Output : Substring: One输出:子串:一
eg例如
string str = null;
string retString = null;
str = "This is substring test";
retString = str.Substring(8, 9);
This return "substring"此返回“子字符串”
simple way to do this in one line of code would be this在一行代码中执行此操作的简单方法是
string sub = input.Substring(input.Length > 5 ? input.Length - 5 : 0);
and here some informations about Operator ?这里有一些关于Operator 的信息? :
:
string input = "OneTwoThree";
(if input.length >5)
{
string str=input.substring(input.length-5,5);
}
In C#
8.0 and later you can use [^5..]
to get the last five characters combined with a ?
在
C#
8.0 及更高版本中,您可以使用[^5..]
将最后五个字符与?
operator to avoid a potential ArgumentOutOfRangeException
.运算符以避免潜在的
ArgumentOutOfRangeException
。
string input1 = "0123456789";
string input2 = "0123";
Console.WriteLine(input1.Length >= 5 ? input1[^5..] : input1); //returns 56789
Console.WriteLine(input2.Length >= 5 ? input2[^5..] : input2); //returns 0123
index-from-end-operator and range-operator index-from-end-operator和range-operator
// Get first three characters
string sub = input.Substring(0, 3);
Console.WriteLine("Substring: {0}", sub); // Output One.
string sub = input.Substring(6, 5);
Console.WriteLine("Substring: {0}", sub); //You'll get output: Three
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.