C# 如何获取字符串的前五个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15941985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the first five character of a String
提问by Knight Wing
I have read this question to get first char of the string. Is there a way to get the first n number of characters from a string in C#?
回答by Habib
You can use Enumerable.Takelike:
你可以使用Enumerable.Take像:
char[] array = yourStringVariable.Take(5).ToArray();
Or you can use String.Substring.
或者您可以使用String.Substring。
string str = yourStringVariable.Substring(0,5);
Remember that String.Substring
could throw an exception in case of string's length less than the characters required.
请记住,String.Substring
如果字符串的长度小于所需的字符,则可能会引发异常。
If you want to get the result back in string then you can use:
如果您想以字符串形式返回结果,则可以使用:
Using String Constructor and LINQ's
Take
string firstFivChar = new string(yourStringVariable.Take(5).ToArray());
使用字符串构造函数和 LINQ
Take
string firstFivChar = new string(yourStringVariable.Take(5).ToArray());
The plus with the approach is not checking for length before hand.
这种方法的优点是无需事先检查长度。
- The other way is to use
String.Substring
with error checking
- 另一种方法是
String.Substring
与错误检查一起使用
like:
喜欢:
string firstFivCharWithSubString =
!String.IsNullOrWhiteSpace(yourStringVariable) && yourStringVariable.Length >= 5
? yourStringVariable.Substring(0, 5)
: yourStringVariable;
回答by Adil
You can use Substring(int startIndex, int length)
您可以使用Substring(int startIndex, int length)
string result = str.Substring(0,5);
The substring starts at a specified character position and has a specified length. This method does not modify the value of the current instance. Instead, it returns a new string with length characters starting from the startIndex position in the current string, MSDN
子字符串从指定的字符位置开始并具有指定的长度。此方法不会修改当前实例的值。相反,它返回一个新的字符串,从当前字符串中的 startIndex 位置开始, MSDN
What if the source string is less then five characters? You will get exception by using above method. We can put condition to check if the number of characters in string are more then 5 then get first five through Substring. Note I have assigned source string to firstFiveChar variable. The firstFiveChar not change if characters are less then 5, so else part is not required.
如果源字符串少于五个字符怎么办?您将通过使用上述方法获得异常。我们可以使用条件来检查字符串中的字符数是否大于 5,然后通过 Substring 获取前五个。注意我已将源字符串分配给 firstFiveChar 变量。如果字符小于 5,则 firstFiveChar 不会更改,因此不需要其他部分。
string firstFiveChar = str;
If(!String.IsNullOrWhiteSpace(yourStringVariable) && yourStringVariable.Length >= 5)
firstFiveChar = yourStringVariable.Substring(0, 5);
回答by Rajeev Kumar
string str = "GoodMorning"
string strModified = str.Substring(0,5);
回答by TechDo
回答by Steven
The problem with .Substring(,)
is, that you need to be sure that the given string has at least the length of the asked number of characters, otherwise an ArgumentOutOfRangeException
will be thrown.
问题.Substring(,)
是,您需要确保给定的字符串至少具有要求的字符数的长度,否则ArgumentOutOfRangeException
将抛出an 。
Solution 1 (using 'Substring'):
解决方案 1(使用“子字符串”):
var firstFive = stringValue != null ?
stringValue.Substring(0, stringValue.Length >= 5 ? 5 : stringValue.Length) :
null;
The drawback of using .Substring(
is that you'll need to check the length of the given string.
使用的缺点.Substring(
是您需要检查给定字符串的长度。
Solution 2 (using 'Take'):
解决方案 2(使用“Take”):
var firstFive = stringValue != null ?
string.Join("", stringValue.Take(5)) :
null;
Using 'Take'will prevent that you need to check the length of the given string.
使用'Take'将防止您需要检查给定字符串的长度。
回答by Peter
Below is an extension method that checks if a string is bigger than what was needed and shortens the string to the defined max amount of chars and appends '...'.
下面是一个扩展方法,它检查字符串是否大于所需的字符串,并将字符串缩短到定义的最大字符数并附加“...”。
public static class StringExtensions
{
public static string Ellipsis(this string s, int charsToDisplay)
{
if (!string.IsNullOrWhiteSpace(s))
return s.Length <= charsToDisplay ? s : new string(s.Take(charsToDisplay).ToArray()) + "...";
return String.Empty;
}
}
回答by ilter
No one mentioned how to make proper checks when using Substring()
, so I wanted to contribute about that.
没有人提到如何在使用时进行适当的检查Substring()
,所以我想为此做出贡献。
If you don't want to use Linq
and go with Substring()
, you have to make sure that your string is bigger than the second parameter (length) of Substring()
function.
如果您不想使用Linq
并使用Substring()
,则必须确保您的字符串大于Substring()
函数的第二个参数(长度)。
Let's say you need the first 5 characters. You should get them with proper check, like this:
假设您需要前 5 个字符。您应该通过适当的检查来获取它们,如下所示:
string title = "love" // 15 characters
var firstFiveChars = title.Length <= 5 ? title : title.Substring(0, 5);
// firstFiveChars: "love" (4 characters)
Without this check, Substring()
function would throw an exception because it'd iterate through letters that aren't there.
如果没有这个检查,Substring()
函数会抛出一个异常,因为它会遍历不存在的字母。
I think you get the idea...
我想你应该已经明白了...
回答by Viacheslav Avsenev
I don't know why anybody mentioned this. But it's the shortest and simplest way to achieve this.
我不知道为什么有人提到这个。但这是实现这一目标的最短和最简单的方法。
string str = yourString.Remove(n);
n
- number of characters that you need
n
- 您需要的字符数
Example
例子
var zz = "7814148471";
Console.WriteLine(zz.Remove(5));
//result - 78141
回答by Abhishek Jaiswal
Try below code
试试下面的代码
string Name = "Abhishek";
string firstfour = Name.Substring(0, 4);
Response.Write(firstfour);
回答by Nadhirsha bin shaju
I have tried the above answers and the best i think is this one
我已经尝试了上述答案,我认为最好的是这个
@item.First_Name.Substring(0,1)
In this i could get the first letter of the string
在这个我可以得到字符串的第一个字母