# 1) 프로그래밍
문자열 첫번째 검색 문자만 Replace
이꼬모꼬
2010. 9. 30. 10:48
"문자"를 "_"로 변경할때 그냥 문자열에 Replace를 하면 조건에 걸리는것 모두를 변경..
훈스 게시판에 처음 조건에 걸리는것만 바꾸는 메서드가 자바에서 지원이 된다기에...
만들어봤다.
// 사용예!
string ss = "바뀔문자,바뀐문자,바꿔봐요!".ReplaceFirst("문자", "_");
결과 : 바뀔_,바뀐문자,바꿔봐요!".
// 확장 메서드 구현
public static class StringEX
{
public static string ReplaceFirst(this string s, string re, string ch)
{
int offsetIndex = s.IndexOf(re) + re.Length;
string first = s.Substring(0, s.IndexOf(re));
string midle = ch;
string last = s.Substring(s.IndexOf(re) + re.Length, s.Length - offsetIndex);
return string.Concat(first, midle, last);
}
}
훈스 게시판에 처음 조건에 걸리는것만 바꾸는 메서드가 자바에서 지원이 된다기에...
만들어봤다.
// 사용예!
string ss = "바뀔문자,바뀐문자,바꿔봐요!".ReplaceFirst("문자", "_");
결과 : 바뀔_,바뀐문자,바꿔봐요!".
// 확장 메서드 구현
public static class StringEX
{
public static string ReplaceFirst(this string s, string re, string ch)
{
int offsetIndex = s.IndexOf(re) + re.Length;
string first = s.Substring(0, s.IndexOf(re));
string midle = ch;
string last = s.Substring(s.IndexOf(re) + re.Length, s.Length - offsetIndex);
return string.Concat(first, midle, last);
}
}