substring
다른 문자에서 가장 오른쪽에있는 6 개의 문자로 구성된 a 를 어떻게 추출 할 수 있습니까?string
있습니까?
예 : 내 문자열은 "PER 343573"
. 이제 "343573"
.
어떻게 할 수 있습니까?
답변
string SubString = MyString.Substring(MyString.Length-6);
답변
확장 방법을 작성하여 Right(n);
함수 . 함수는 빈 문자열을 반환하는 null 또는 빈 문자열, 원래 문자열을 반환하는 최대 길이보다 짧은 문자열 및 가장 오른쪽 문자의 최대 길이를 반환하는 최대 길이보다 긴 문자열을 처리해야합니다.
public static string Right(this string sValue, int iMaxLength)
{
//Check if the value is valid
if (string.IsNullOrEmpty(sValue))
{
//Set valid empty string as string could be null
sValue = string.Empty;
}
else if (sValue.Length > iMaxLength)
{
//Make the string no longer than the max length
sValue = sValue.Substring(sValue.Length - iMaxLength, iMaxLength);
}
//Return the string
return sValue;
}
답변
확장 방법을 사용하는 것이 더 좋을 것입니다.
public static class StringExtensions
{
public static string Right(this string str, int length)
{
return str.Substring(str.Length - length, length);
}
}
용법
string myStr = "PER 343573";
string subStr = myStr.Right(6);
답변
using System;
public static class DataTypeExtensions
{
#region Methods
public static string Left(this string str, int length)
{
str = (str ?? string.Empty);
return str.Substring(0, Math.Min(length, str.Length));
}
public static string Right(this string str, int length)
{
str = (str ?? string.Empty);
return (str.Length >= length)
? str.Substring(str.Length - length, length)
: str;
}
#endregion
}
오류가 발생하지 않으면 null을 빈 문자열로 반환하고 잘린 값 또는 기본 값을 반환합니다. “testx”.Left (4) 또는 str.Right (12);
답변
답변
문자열의 길이는 확실하지 않지만 단어 수 (이 경우에는 ‘xxx yyyyyy’와 같이 항상 2 단어)를 알고 있다면 split을 사용하는 것이 좋습니다.
string Result = "PER 343573".Split(" ")[1];
이것은 항상 문자열의 두 번째 단어를 반환합니다.
답변
이것은 정확히 당신이 요구하는 것은 아니지만 예제를 보면 문자열의 숫자 섹션을 찾고있는 것 같습니다.
이것이 항상 그런 경우라면 정규 표현식을 사용하는 것이 좋습니다.
var regex= new Regex("\n+");
string numberString = regex.Match(page).Value;
