문자열 함수 확장replace, indexof
1716 단어 replace
public static class StringExtensions
{
public static int IndexOfTimes(this string s, string value, int times)
{
return s.IndexOfTimes(value, 0, times);
}
public static int IndexOfTimes(this string s, string value, int startindex, int times)
{
if (string.IsNullOrEmpty(s)) return -1;
startindex = startindex < 0 ? 0 : startindex;
if (times <= 0)
return -1;
int at = 0;
int count = 0;
while (startindex < s.Length)
{
at = s.IndexOf(value, startindex);
if (at == -1)
return -1;
count++;
if (count == times)
return at;
startindex = at + 1;
}
return -1;
}
public static string ReplaceFirst(this string s, string oldValue, string newValue)
{
return s.ReplaceTime(oldValue, newValue, 1);
}
public static string ReplaceTime(this string s, string oldValue, string newValue, int times)
{
int pos=s.IndexOfTimes(oldValue, times);
if (pos < 0)
return s;
if (string.IsNullOrEmpty(newValue))
return "";
s = s.Remove(pos, oldValue.Length);
s = s.Insert(pos, newValue);
return s;
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Java에서 replace, replaceAll, replaceFirst 함수의 사용법 소결두 매개 변수는 문자열입니다. ・replaceFirst(String regex, String replacement), 기본은 ReplaceAll과 같고, 차이점은 첫 번째 일치 항목만 바꾸는 것입니다. 그리고 "a"...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.