문자열이 너무 긴 경우“…”로 어떻게자를 수 있습니까?
누군가가 좋은 아이디어를 가지고 있기를 바랍니다. 다음과 같은 문자열이 있습니다.
abcdefg
abcde
abc
내가 필요한 것은 지정된 길이보다 더 많은 경우 다음과 같이 표시되도록 잘리는 것입니다.
abc ..
abc ..
abc
이를 위해 사용할 수있는 간단한 C # 코드가 있습니까?
다음은 확장 메서드에 래핑 된 논리입니다.
public static string Truncate(this string value, int maxChars)
{
return value.Length <= maxChars ? value : value.Substring(0, maxChars) + "...";
}
용법:
var s = "abcdefg";
Console.WriteLine(s.Truncate(3));
public string TruncString(string myStr, int THRESHOLD)
{
if (myStr.Length > THRESHOLD)
return myStr.Substring(0, THRESHOLD) + "...";
return myStr;
}
실제로 THRESHOLD 변수가 필요하거나 항상 동일한 크기 인 경우에 대비하여 명명 규칙을 무시하십시오.
또는
string res = (myStr.Length > THRESHOLD) ? myStr.Substring(0, THRESHOLD) + ".." : myStr;
모두 매우 좋은 대답이지만, 문자열이 문장 인 경우 조금만 정리하려면 단어 중간에서 문자열을 끊지 마십시오.
private string TruncateForDisplay(this string value, int length)
{
if (string.IsNullOrEmpty(value)) return string.Empty;
var returnValue = value;
if (value.Length > length)
{
var tmp = value.Substring(0, length) ;
if (tmp.LastIndexOf(' ') > 0)
returnValue = tmp.Substring(0, tmp.LastIndexOf(' ') ) + " ...";
}
return returnValue;
}
이 작업을 수행하는 .NET Framework에는 기본 제공 메서드가 없지만 직접 작성하는 것은 매우 쉬운 방법입니다. 여기에 단계가 있습니다. 직접 만들어보고 결과를 알려주십시오.
메서드, 아마도 확장 메서드 만들기
public static void TruncateWithEllipsis(this string value, int maxLength)
전달 된 값이 속성을
maxLength
사용하여 지정된 값보다 큰지 확인합니다 . 경우 보다 크지 단지를 반환합니다 .Length
value
maxLength
value
전달 된 값을있는 그대로 반환하지 않으면 잘라야한다는 것을 알 수 있습니다. 따라서
SubString
메서드를 사용하여 문자열의 더 작은 섹션을 가져와야합니다 . 이 메서드는 지정된 시작 및 종료 값을 기반으로 문자열의 더 작은 섹션을 반환합니다. 끝 위치는maxLength
매개 변수 에 의해 전달 된 것이므로 사용하십시오.문자열의 하위 섹션과 생략 부호를 반환합니다.
나중에 좋은 연습은 방법을 업데이트하고 전체 단어 후에 만 중단되도록하는 것입니다. 또한 오버로드를 생성하여 문자열이 잘린 것을 표시 할 방법을 지정할 수 있습니다. 예를 들어, 응용 프로그램이 클릭하여 더 자세한 정보를 표시하도록 설정된 경우 메서드는 "..."대신 "(더 보려면 클릭)"을 반환 할 수 있습니다.
다음은 타원의 길이를 설명하는 버전입니다.
public static string Truncate(this string value, int maxChars)
{
const string ellipses = "...";
return value.Length <= maxChars ? value : value.Substring(0, maxChars - ellipses.Length) + ellipses;
}
뒤에있는 코드 :
string shorten(sting s)
{
//string s = abcdefg;
int tooLongInt = 3;
if (s.Length > tooLongInt)
return s.Substring(0, tooLongInt) + "..";
return s;
}
마크 업 :
<td><%= shorten(YOUR_STRING_HERE) %></td>
그 목적을 위해 메소드를 구현하는 것이 더 낫습니다.
string shorten(sting yourStr)
{
//Suppose you have a string yourStr, toView and a constant value
string toView;
const int maxView = 3;
if (yourStr.Length > maxView)
toView = yourStr.Substring(0, maxView) + " ..."; // all you have is to use Substring(int, int) .net method
else
toView = yourStr;
return toView;
}
string s = "abcdefg";
if (s.length > 3)
{
s = s.substring(0,3);
}
Substring 함수를 사용할 수 있습니다.
"C # truncate ellipsis"를 검색 한 후이 질문을 찾았습니다. 다양한 답변을 사용하여 다음과 같은 기능으로 나만의 솔루션을 만들었습니다.
- 확장 방법
- 줄임표 추가
- 줄임표를 선택 사항으로 설정
자르기를 시도하기 전에 문자열이 널 또는 비어 있지 않은지 확인하십시오.
public static class StringExtensions { public static string Truncate(this string value, int maxLength, bool addEllipsis = false) { // Check for valid string before attempting to truncate if (string.IsNullOrEmpty(value)) return value; // Proceed with truncating var result = string.Empty; if (value.Length > maxLength) { result = value.Substring(0, maxLength); if (addEllipsis) result += "..."; } else { result = value; } return result; } }
다른 사람에게 도움이되기를 바랍니다.
Sure, here is some sample code:
string str = "abcdefg";
if (str.Length > X){
str = str.Substring(0, X) + "...";
}
I has this problem recently. I was storing a "status" message in a nvarcharMAX DB field which is 4000 characters. However my status messages were building up and hitting the exception.
But it wasn't a simple case of truncation as an arbitrary truncation would orphan part of a status message, so I really needed to "truncate" at a consistent part of the string.
I solved the problem by converting the string to a string array, removing the first element and then restoring to a string. Here is the code ("CurrentStatus" is the string holding the data)...
if (CurrentStatus.Length >= 3750)
{
// perform some truncation to free up some space.
// Lets get the status messages into an array for processing...
// We use the period as the delimiter, then skip the first item and re-insert into an array.
string[] statusArray = CurrentStatus.Split(new string[] { "." }, StringSplitOptions.None)
.Skip(1).ToArray();
// Next we return the data to a string and replace any escaped returns with proper one.
CurrentStatus = (string.Join(".", statusArray))
.Replace("\\r\\n", Environment.NewLine);
}
Hope it helps someone out.
'code' 카테고리의 다른 글
jQuery 이벤트 .load (), .ready (), .unload () (0) | 2020.10.29 |
---|---|
Class 객체 (java.lang.Class)는 무엇입니까? (0) | 2020.10.29 |
Android에서 아랍어 텍스트를 지원하는 방법은 무엇입니까? (0) | 2020.10.29 |
새 페이지로 리디렉션하는 aspx 페이지 (0) | 2020.10.28 |
C #에서 try / finally 오버 헤드? (0) | 2020.10.28 |