본문 바로가기

프로그래밍/iOS,macOS

NSString 문자열 관련/정규식/텍스트뷰 등...

문자열 타입변환

NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];

NSString *string = [[NSData alloc] initWithData:data encoding:NSUTF8StringEncoding];

const char *str = [string UTF8String];

NSData *data = [NSData dataWithBytes:str length:strlen(str)+1];





문자열을분리

문자열을 배열로 분리

-(NSArray<NSString*>*)componentsSeparatedByString:(NSString*)separator;


반대로 배열을 문자열로

-(NSString*)componentsJoinedByString:(NSString*)separator;


여러개의 토큰으로 분리

componentsSeparatedByCharactersInset:[NSCharacterSet characterSetWithCharactersInString:@",;:"]];


NSCharacterSet 에는 여러가지 타입 프로퍼티를 제공한다.

예를들어 행전환은 [NSCharacterSet newlineCharacterSet] 이다.



문자열합치기

[string stringByAppendingString:string2];




문자열 교체

NSString *result=[string stringByReplacingOccurrencesOfString:@"원본" withString:@"교체"];

NSString *result=[string stringByReplacingCharactersInRange:(NSRange)range withString:@"교체"];


NSMutableString 은 자체적으로 수정이 가능.

[string replaceOccurrencesOfString:@"원본" withString:@"교체" options: range:];

[string replaceCharactersInRange:range withString:@"교체"];






정규식

NSString 정규식 검색

NSRange range = [string rangeOfString:@"정규식" options:NSRegularExpressionSearch];

NSString *result = [string substringWithRange:range];




NSRegularExpression

NSError *error = nil;

NSRegularExpression *regexp = 

[NSRegularExpression regularExpressionWithPattern:@"정규식패턴"

options:0    // NSRegularExpressionOption

error:&error];


대소문자 구분제외 = options:NSRegularExpressionCaseInsensitive 




일치하는 항목수 얻기

NSUInteger numberOfMatches = 

[regexp numberOfMatchesInString:string options:0 range:NSMakeRange(0, string.legth)];




매칭 블럭으로 NSTextCheckingResult 처리

[regexp enumerateMatchesInString:string

options:0             // NSMatchingOptions

range:NSMakeRange(0,string.leng)] 

usingBlock:^(NSTextCheckingResult *match, NSMatchingFlag flag, BOOL *stop)

{


}];



NSTextCheckingResult

문자열에 여러개의 매칭 항목을 처리하기 위해서 사용한다. 캡처그룹이 있는 경우 NSTextCheckingResult 에 각 그룹별 NSRange 배열이 생성된다.



일치하는 첫번째 항목

NSTextCheckingResult *match = 

[regexp firstMatchInString:string

options:0            // NSMatchingOptions

range:NSMakeRange(0, string.length)];


일치하는 항목 수(그룹)

match.numberOfRanges


그룹별 접근

NSRange *range = [match rangeAtIndex:0]



NSTextCheckingResult 배열

NSArray<NSTextCheckingResult*> *matches =

 [regexp matchesInString:str options:0 range:NSMakeRange(0, string.length)];


for( NSTextCheckingResult *match in matches ) {

.

.

NSTextCheckingResult는 range값을 가지고 있으므로, 해당 항목을 가져오려면

NSString *result = [string substringWithRange:match.range];

.

.

}




정규식으로 문자열 교체

템플릿은 변경할 문자열이고, $0, $1, $2 등으로 그룹을 지정할 수 있다.

NSString *restul = [regexp stringByReplacingMatchesInString:string

options:0

range:NSMakeRange(0, string.length)

withTemplate:@"템플릿"];



검색된 문자열별로 서로 다른 처리등을 하기 위해서는 어쩔수 없이 뺑뱅이 돌려야 할듯 싶다.

머리를 짜내도 정규식으로 표현이 안된다 -_-;;;;







NSAttributedString

속성을 키로 해서 NSDictionary에 저장한 뒤 해당 속성을 NSAttributedString에 지정해주면 된다.

주요속성 키:값

NSFontAttributeName : UIFont

NSForegroundColorAttributeName : UIColor

NSBackgroundColorAttributeName : UIColor

NSStrokeWidthAttributeName : NSNumber

NSStrokeColorAttributeName : UIColor

NSUnderlineStyleAttributeName : NSNumber

NSUnderlineColorAttributeName : UIColor

NSStrikethroughStyleAttributeName : NSNumber

NSStrikethroughColorAttributeName : UIColor


NSMutableDictionary *attribute = [NSMutabledictionary dictionary];

attribute[NSFontAttributeName] = [UIFont systemFontOfSize:10];

attribute[NSForegroundColorAttributeName] = [UIColor redColor];


NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:string];

[string setAttributes:attribute range:NSMakeRange(0, string.length )];

 


HTML String to NSAttributedString 

NSString *html = @"<font size="12">안녕</font>하세요.<s>안드로이드</s>iOS 개발중입니다.";

NSAttributedString *string = 

[[NSAttributedString alloc] 

initWithData:[html dataUsingEncoding:NSUTF8StringEncoding]

options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,

NSCharacterEncodingDocumentAttribute:@(NSUTF8StringEncoding)}

documentAttributes:nil

error:nil];





UITextView에서 delete 감지

delegate 메쏘드인 shouldChangeTextInRange 에서 다음과 같이 delete 가 눌렸는지 확인가능하다.


const char * _char = [replacementText cStringUsingEncoding:NSUTF8StringEncoding];

if( strcmp(_char,"\b") == -8 ) {

// 삭제 터치됨.

}