C#의 문자열에서 마지막 4자를 가져오려면 어떻게 해야 합니까?
내게 줄이 있다고 가정하자,
"34234234d124"
네▁theers▁which▁charact▁of▁get▁to▁want▁i를 얻고 싶습니다."d124"
사용할 수 있습니다SubString
변수의 이름을 지정하는 것을 포함하여 몇 줄의 코드가 필요합니다.
이 결과를 C#으로 한 식으로 얻을 수 있습니까?
mystring.Substring(Math.Max(0, mystring.Length - 4)); //how many lines is this?
만약 당신이 문자열의 길이가 적어도 4라면, 그것은 더 짧습니다:
mystring.Substring(mystring.Length - 4);
확장 방법을 사용할 수 있습니다.
public static class StringExtension
{
public static string GetLast(this string source, int tail_length)
{
if(tail_length >= source.Length)
return source;
return source.Substring(source.Length - tail_length);
}
}
그런 다음 전화합니다.
string mystring = "34234234d124";
string res = mystring.GetLast(4);
2020년 업데이트: C# 8.0을 사용하면 다음과 같은 이점을 얻을 수 있습니다.
> "C# 8.0 finally makes this easy"[^4..]
"easy"
동일한 방법으로 배열을 슬라이스할 수도 있습니다. 인덱스 및 범위를 참조하십시오.
당신이 해야 할 일은..
String result = mystring.Substring(mystring.Length - 4);
좋아요, 그럼 이 게시물은 오래된 게시물인 것 같네요, 그런데 왜 우리는 프레임워크에 이미 제공된 코드를 작성하고 있습니다.
프레임워크 DLL "Microsoft"에 대한 참조를 추가할 것을 제안합니다.비주얼 베이직"
using Microsoft.VisualBasic;
//...
string value = Strings.Right("34234234d124", 4);
string mystring = "34234234d124";
mystring = mystring.Substring(mystring.Length-4)
Substring을 사용하는 것은 실제로 상당히 짧고 읽을 수 있습니다.
var result = mystring.Substring(mystring.Length - Math.Min(4, mystring.Length));
// result == "d124"
실행 지연으로 인해 성능이 저하되지 않아야 하는 또 다른 대안이 있습니다.
new string(mystring.Reverse().Take(4).Reverse().ToArray());
적을위한확방장만지법 의 확장 방법.mystring.Last(4)
일이 좀 더 많지만, 가장 깨끗한 해결책입니다.
간단히 사용할 수 있습니다.Substring
예를 C#은예를 들면.
string str = "1110000";
string lastFourDigits = str.Substring((str.Length - 4), 4);
결과 0000이 반환됩니다.
간단한 솔루션은 다음과 같습니다.
string mystring = "34234234d124";
string last4 = mystring.Substring(mystring.Length - 4, 4);
정의:
public static string GetLast(string source, int last)
{
return last >= source.Length ? source : source.Substring(source.Length - last);
}
용도:
GetLast("string of", 2);
결과:
의
string var = "12345678";
var = var[^4..];
// var = "5678"
이것은 문자 그대로 "마지막 네 문자를 끝(^4)에서 끝(...)까지 가져가라"를 의미하는 인덱스 연산자입니다.
mystring = mystring.Length > 4 ? mystring.Substring(mystring.Length - 4, 4) : mystring;
일부 이전 답변과 비교했을 때 주요 차이점은 입력 문자열이 다음과 같을 때 이 코드 조각을 고려한다는 것입니다.
- Null
- 요청된 길이보다 길거나 일치합니다.
- 요청한 길이보다 짧습니다.
여기 있습니다.
public static class StringExtensions
{
public static string Right(this string str, int length)
{
return str.Substring(str.Length - length, length);
}
public static string MyLast(this string str, int length)
{
if (str == null)
return null;
else if (str.Length >= length)
return str.Substring(str.Length - length, length);
else
return str;
}
}
바로 다음과 같습니다.
int count = 4;
string sub = mystring.Substring(mystring.Length - count, count);
C# 8 이상에서 새로운 범위를 사용하는 것을 언급하는 기존 답변을 확장하고 싶습니다.코드를 4보다 짧은 문자열이라도 가능한 모든 문자열에 사용할 수 있도록 하려면 어떤 형태로든 조건이 필요합니다!만약 당신이 코드를 복사하고 싶다면, 저는 예 5나 6을 제안합니다.
string mystring ="C# 8.0 finally makes slicing possible";
1: 끝 부분을 자르는 것 - 처음부터 생략할 문자 수를 지정함 - 이것은 VS 2019가 제안하는 것입니다.
string example1 = mystring[Math.Max(0, mystring.Length - 4)..] ;
2: 끝 부분을 자르는 것 - 끝에서 몇 글자를 취할 것인지 지정함으로써:
string example2 = mystring[^Math.Min(mystring.Length, 4)..] ;
3: 끝 부분을 슬라이싱 - Max/Min을 ?: 연산자로 대체:
string example3 = (mystring.length > 4)? mystring[^4..] : mystring);
저는 개인적으로 첫 번째보다 두 번째와 세 번째 변형을 더 좋아합니다.
무효? 하지만 우리는 보편성에 대해 아직 끝나지 않았습니다.지금까지의 모든 예제는 null 문자열에 대한 예외를 발생시킵니다.null(C#8 이상의 null이 아닌 문자열을 사용하지 않는 경우)을 고려하고 'if'(기존 예 'if'가 다른 답변에 이미 나와 있음) 없이 수행하려면 다음이 필요합니다.
4: null을 고려한 슬라이싱 - 생략할 문자 수 지정:
string example4 = mystring?[Math.Max(0, mystring.Length - 4)..] ?? string.Empty;
5: null을 고려한 슬라이싱 - 사용할 문자 수를 지정합니다.
string example5 = mystring?[^Math.Min(mystring.Length, 4)..] ?? string.Empty;
6: ?: 연산자(및 두 개의 다른 '?' 연산자)를 사용하여 null을 고려하는 슬라이싱 ;-):
(WriteLine과 같은 문자열 보간에는 전체를 넣을 수 없습니다.)
string example6 = (mystring?.Length > 4) ? filePath[^4..] : mystring ?? string.Empty;
7: C# 6 또는 7.x에 대해 좋은 구형 Substring()을 가진 동등한 변형:
(WriteLine과 같은 문자열 보간에는 전체를 넣을 수 없습니다.)
string example7 = (mystring?.Length > 4) ? mystring.Substring(mystring.Length- 4) : mystring ?? string.Empty;
우아한 타락?저는 C#의 새로운 기능이 마음에 듭니다.마지막 예와 같이 한 줄에 놓는 것은 다소 지나쳐 보일 수 있습니다.우리는 결국 약간 펄처럼 변했죠, 그렇죠?하지만 이것은 학습을 위한 좋은 예이며 저는 시험된 도서관 방법으로 한 번 사용해도 좋습니다.더 좋은 것은 현대 C#에서 이러한 모든 null 특정 처리를 원하지 않고 피한다면 null을 제거할 수 있다는 것입니다.
바로 가기와 같은 라이브러리/확장 방법은 정말 유용합니다.C#의 발전에도 불구하고 위의 코드를 반복하는 것보다 사용하기 쉬운 것을 얻기 위해서는 작은 문자열 조작 필요에 따라 직접 작성해야 합니다.
저는 베이직으로 시작한 사람 중 한 명이며, 40년 전에 이미 Right$(,)가 있었습니다.Strings를 사용하는 것이 가능하다는 것이 재미있습니다.다른 답변에 표시된 것처럼 C#이 있는 VB의 오른쪽(,)도 마찬가지입니다.
C#은 (이전의 BASIC과는 반대로) 정상적인 열화보다 정밀도를 선택했습니다.따라서 이 답변에서 원하는 모든 적절한 변형을 복사하고 자신을 위한 우아한 바로 가기 기능을 정의하십시오. 내 것은 RightChars(int)라는 확장 기능입니다.
문자열에 요청된 양보다 적은 문자가 있으면 오류가 없으므로 이 방법이 유용합니다.
using System.Linq;
string.Concat("123".TakeLast(4));
이것은 어떤 길이의 문자열에서도 실패하지 않습니다.
string mystring = "34234234d124";
string last4 = Regex.Match(mystring, "(?!.{5}).*").Value;
// last4 = "d124"
last4 = Regex.Match("d12", "(?!.{5}).*").Value;
// last4 = "d12"
이것은 아마도 당면한 작업에 대해 과도한 기능일 수 있지만, 추가적인 유효성 검사가 필요한 경우 정규식에 추가할 수 있습니다.
편집: 이 정규식이 더 효율적일 것 같습니다.
@".{4}\Z"
거리 측정기를 사용하는 것이 저에게 가장 쉬운 방법입니다.많은 코드가 필요하지 않습니다.
당신의 경우, 당신은 다음과 같이 당신이 원하는 것을 참조하십시오.
// the ^ operator indicates the element position from the end of a sequence
string str = "34234234d124"[^4..]
string x = "34234234d124";
string y = x.Substring(x.Length - 4);
일반 사용Last<T>
그것은 모든 것과 함께 작동할 것입니다.IEnumerable
끈 포함.
public static IEnumerable<T> Last<T>(this IEnumerable<T> enumerable, int nLastElements)
{
int count = Math.Min(enumerable.Count(), nLastElements);
for (int i = enumerable.Count() - count; i < enumerable.Count(); i++)
{
yield return enumerable.ElementAt(i);
}
}
그리고 문자열에 대한 구체적인 것은
public static string Right(this string str, int nLastElements)
{
return new string(str.Last(nLastElements).ToArray());
}
TakeLast 메서드(예: new String(텍스트)를 사용하는 것이 좋습니다.Take Last(4).대상 배열()
저는 당신이 원하는 결과를 얻을 수 있는 다양한 소스에서 수정된 코드를 조합했습니다. 그 외에도 더 많은 것을 할 수 있습니다.음의 int 값, 문자열 길이를 초과하는 int 값 및 시작 인덱스보다 작은 끝 인덱스를 허용했습니다.마지막 경우 메소드는 역순 하위 문자열을 반환합니다.댓글이 많은데 뭔가 석연치 않은 부분이 있거나 그냥 미친 부분이 있으면 알려주세요.제가 이걸 어디에 쓸지 보려고 이걸 가지고 놀고 있었어요.
/// <summary>
/// Returns characters slices from string between two indexes.
///
/// If start or end are negative, their indexes will be calculated counting
/// back from the end of the source string.
/// If the end param is less than the start param, the Slice will return a
/// substring in reverse order.
///
/// <param name="source">String the extension method will operate upon.</param>
/// <param name="startIndex">Starting index, may be negative.</param>
/// <param name="endIndex">Ending index, may be negative).</param>
/// </summary>
public static string Slice(this string source, int startIndex, int endIndex = int.MaxValue)
{
// If startIndex or endIndex exceeds the length of the string they will be set
// to zero if negative, or source.Length if positive.
if (source.ExceedsLength(startIndex)) startIndex = startIndex < 0 ? 0 : source.Length;
if (source.ExceedsLength(endIndex)) endIndex = endIndex < 0 ? 0 : source.Length;
// Negative values count back from the end of the source string.
if (startIndex < 0) startIndex = source.Length + startIndex;
if (endIndex < 0) endIndex = source.Length + endIndex;
// Calculate length of characters to slice from string.
int length = Math.Abs(endIndex - startIndex);
// If the endIndex is less than the startIndex, return a reversed substring.
if (endIndex < startIndex) return source.Substring(endIndex, length).Reverse();
return source.Substring(startIndex, length);
}
/// <summary>
/// Reverses character order in a string.
/// </summary>
/// <param name="source"></param>
/// <returns>string</returns>
public static string Reverse(this string source)
{
char[] charArray = source.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
/// <summary>
/// Verifies that the index is within the range of the string source.
/// </summary>
/// <param name="source"></param>
/// <param name="index"></param>
/// <returns>bool</returns>
public static bool ExceedsLength(this string source, int index)
{
return Math.Abs(index) > source.Length ? true : false;
}
"이것은 확장 방법입니다."와 같은 문자열이 있으면 몇 가지 예와 결과가 있습니다.
var s = "This is an extension method";
// If you want to slice off end characters, just supply a negative startIndex value
// but no endIndex value (or an endIndex value >= to the source string length).
Console.WriteLine(s.Slice(-5));
// Returns "ethod".
Console.WriteLine(s.Slice(-5, 10));
// Results in a startIndex of 22 (counting 5 back from the end).
// Since that is greater than the endIndex of 10, the result is reversed.
// Returns "m noisnetxe"
Console.WriteLine(s.Slice(2, 15));
// Returns "is is an exte"
이 버전이 누군가에게 도움이 되기를 바랍니다.음수를 사용하지 않는 경우에도 정상적으로 작동하며 범위를 벗어난 파라미터에 대한 기본값을 제공합니다.
string var = "12345678";
if (var.Length >= 4)
{
var = var.substring(var.Length - 4, 4)
}
// result = "5678"
마지막 문자에서 10자에 위치한 문자열 사이에 문자열을 삽입하고 3자만 필요하다고 가정합니다.
예를 들어StreamSelected = "rtsp://72.142.0.230:80/SMIL-CHAN-273/4CIF-273.stream"
위에서, 나는 추출할 필요가 있습니다."273"
데이터베이스 쿼리에 사용할 정보
//find the length of the string
int streamLen=StreamSelected.Length;
//now remove all characters except the last 10 characters
string streamLessTen = StreamSelected.Remove(0,(streamLen - 10));
//extract the 3 characters using substring starting from index 0
//show Result is a TextBox (txtStreamSubs) with
txtStreamSubs.Text = streamLessTen.Substring(0, 3);
public static string Last(this string source, int tailLength)
{
return tailLength >= source.Length ? source : source[^tailLength..];
}
이것은 OP 질문 이상이지만 문자열의 마지막 3개를 특정 목적으로 사용하는 방법에 대한 예입니다.저의 경우 문자열(1~3자리 숫자)로 저장되는 숫자 필드에 대해 숫자 정렬(LINQ OrderBy)을 하고 싶었습니다.따라서 문자열 번호를 숫자처럼 정렬하려면 문자열 번호를 0으로 왼쪽 패딩한 다음 마지막 3개를 사용해야 합니다.결과 OrderBy 문은 다음과 같습니다.
myList = myList.OrderBy(x => string.Concat("00",x.Id)[^3..])
끈이.OrderBy 문에 사용된 Concat()는 "001", "002", "011", "021", "114"와 같은 문자열을 생성하여 숫자로 저장된 경우와 같은 방식으로 정렬합니다.
언급URL : https://stackoverflow.com/questions/6413572/how-do-i-get-the-last-four-characters-from-a-string-in-c
'programing' 카테고리의 다른 글
zure Active Directory에서 응용 프로그램을 삭제하려면 어떻게 해야 합니까? (0) | 2023.05.08 |
---|---|
명령줄(단말기)에서 R 스크립트를 사용하는 가장 좋은 방법은 무엇입니까? (0) | 2023.05.08 |
다트의 평등에 대한 목록을 어떻게 비교할 수 있습니까? (0) | 2023.05.03 |
"앱스토어 연결 작업 오류 ITMS-90771" 수정 방법 (0) | 2023.05.03 |
Azure 함수에 대한 다중 트리거 (0) | 2023.05.03 |