Replace : 바꾸다, 대체하다, 교체하다
말 그대로 문자열안의 값을 원하는 값으로 교체해주는 메서드이다.
여러가지 오버로드가 존재하지만 가장 많이 사용하는, 문자열 교체 오버로드를 살펴보기로 하자
String.Replace("문자열 내 바꾸려는 싶은 문자열", "교체하는 문자열")
using System;
namespace forTest
{
internal class Test
{
static void Main(string[] args)
{
string s1 = "HelloWorld";
string s2 = "I'm Robot";
string s3 = "Nice to Meet you\n";
string s4 = "Have a nice day";
string repS1 = s1.Replace("World", " Ugly^^");
string repS2 = s2.Replace("'m Robot", " am your father");
string repS3 = s3.Replace("Nice", "\r\r\n\nI'm really annoyed11111111 "); //trim을 보여주기 위해 일부러 공백 추가함
string repS4 = s4.Replace("nice", "really shitty");
Console.WriteLine(repS1);
Console.WriteLine(repS2);
Console.WriteLine(repS3);
Console.WriteLine(repS4);
}
}
}
이렇게 빈칸과 첫번째 인자값에 들어간 문자를 두번째 인자값으로 대체 하는 함수이다.
이걸 이용해서 문자 중간중간에 비어있는 빈칸도 제거해 줄 수 있다.
해당 문자열을 기준으로 앞,뒤 모든 공백을 제거해주는 메서드이다
대신 문자열 중간중간에 있는 빈칸은 제거 불가
char값을 이용해서 문자를 지울수도 있다.
String.Trim()
, String.Trim('char')
이렇게 일반적인 Trim도 있고
앞쪽만 지워주는 TrimStart, 뒷쪽만 지워주는 TrimEnd도 존재한다
using System;
namespace forTest
{
internal class Test
{
static void Main(string[] args)
{
string s1 = "HelloWorld";
string s2 = "I'm Robot";
string s3 = "Nice to Meet you\n";
string s4 = "Have a nice day";
string repS1 = s1.Replace("World", " Ugly^^");
string repS2 = s2.Replace("'m Robot", " am your father");
string repS3 = s3.Replace("Nice", "\r\r\n\n111111111I'm really annoyed "); //trim을 보여주기 위해 일부러 공백 추가함
string repS4 = s4.Replace("nice", "really shitty");
string trimRepS3 = repS3.Trim();
string trimTrimStartRep3 = trimRepS3.TrimStart('1');
Console.WriteLine("Trim 전 : " + repS3);
Console.WriteLine("공백제거 Trim 후 : " + trimRepS3 + "\n");
Console.WriteLine("앞쪽 1제거 TrimStart 후 : " + trimTrimStartRep3);
}
}
}
이렇게 잘 출력된다!
Replace랑 Trim이랑 참 좋은 기능이다!