NSString 문자열 다루기 정리

개발/iOS 2017. 9. 13. 19:09
반응형

String 관련 메소드를 사용하다가 헷갈리거나 기억이 잘 안나는 메소드가 있습니다.

이러한 메소드 및 간략한 사용법을 살펴보겠습니다.

메소드 설명은 빈번하거나 자주 까먹는 메소드 순으로 나열했습니다.


스트링 내 특정 문자열이 있는지 검사
1
2
3
4
5
6
7
8
9
10
11
12
13
14
NSString *str1 = @"Hello World!!";
NSRange stRange;
stRange = [str1 rangeOfString:@"Wo"];
 
if (stRange.location == NSNotFound)
{
    NSLog(@"Not Fund String!!");
}
else
{
    NSLog(@"location : %d", (int)stRange.location); // 6
    NSLog(@"length : %d", (int)stRange.length);     // 2
}
 
cs

----결과-----

location : 6

length : 2


특정 문자열로 배열로 분리하기 (split)

1
2
3
4
5
6
7
8
9
10
11
12
NSString *str1 = @"Hello|World|!!";    
NSArray *arr = [str1 componentsSeparatedByString:@"|"];
 
if (arr != nil)
{
    int nCnt = (int)[arr count];
 
    for (int i=0; i<nCnt; ++i)
    {
        NSLog(@"arr[%d] = %@", i, [arr objectAtIndex:i]);
    }
}
cs


----결과----

arr[0] = Hello
arr[1] = World
arr[2] = !!


아래와 같이 예외 사항을 케이스를 살펴보겠습니다.

안드로이드와 다르게 동작하는게 있으니 구현하실때 주의 하도록 합시다.


1) 케이스 1

1
str1 = @"Hello World!!";

cs


----결과----

arr[0] = HelloWorld!!


2) 케이스 2

1
str1 = @"Hello||World!!";

cs


----결과----

arr[0] = Hello
arr[1] =
arr[2] = World!!


3) 케이스 3

1
str1 = @"||";

cs


----결과----

arr[0] = 

arr[1] =

arr[2] =



특정 영역가져오기 (substring)

1
2
3
4
NSString *str1 = @"Hello World!!";
NSString *str2 = [str1 substringWithRange:NSMakeRange(65)];
 
NSLog(@"str2 = %@", str2);
cs


----결과----

str2 = World


NSData -> NSString 변환

1
NSString *str1 = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
cs


NSString -> NSData 변환

1
NSData *data = [str1 dataUsingEncoding:NSUTF8StringEncoding];
cs


치환하기 (replace)

1
2
3
4
5
NSString *str1 = @"Hello World!!";
NSString *str2;
 
str2 = [str1 stringByReplacingOccurrencesOfString:@"!!" withString:@"@@"];
NSLog(@"str2 = %@", str2);
cs


----결과----

str2 = Hello World@@


앞부분 부터 비교하기

1
2
3
4
5
6
NSString *str1 = @"Hello World!!";
    
if ([str1 hasPrefix:@"Hel"])
{
    
}
cs


뒷부분 부터 비교하기
1
2
3
4
5
6
NSString *str1 = @"Hello World!!";
      
if ([str1 hasSuffix:@"d!!"])
{
 
}
cs


일단 이정도로만 정리하도록 하겠습니다.

앞으로 작업하다가 사용법이 까다롭거나 자주 까먹는 메소드는 추가해서 정리하도록 하겠습니다.


반응형
admin