11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

iOSでの文字列処理

Last updated at Posted at 2014-02-28

比較

  • NSString同士であれば、isEqualTo: より、 isEqualToString: の方が高速(公式ドキュメントより)

NSStringによる処理

  • 前後の空白文字を削除.
str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

NSMutableStringによる処理

  • 置換
NSMutableString*	tempString	= [NSMutableString stringWithString:defaultString];
// スラッシュ区切りをハイフン区切りに.
[tempString replaceOccurrencesOfString:@"/"
							withString:@"-"
							options:0
							range:NSMakeRange(0, [tempString length])];

標準ライブラリ:NSRegularExpression

概要

正規表現は、iOS 4.0以降で、標準ライブラリに組み込まれた。

使い方

  • 正規表現をつくる
NSError* error = nil;
NSRegularExpression* regex =
	[NSRegularExpression regularExpressionWithPattern:@"abcd"
		options:NSRegularExpressionCaseInsensitive
		error:&error
	];
  • マッチしたかどうかを調べる(レンジを調べる)
NSRange rangeOfFirstMatch =
	[regex rangeOfFirstMatchInString:string
		options:0
		range:NSMakeRange(0, [string length])
	];
if( !NSEqualRanges(rangeOfFirstMatch,
		NSMakeRange(NSNotFound,0) ) )
{
	// マッチ!
	NSString* strMatch = [string substringWithRange:rangeOfFirstMatch];
}
  • マッチした数を調べる
NSUInteger numberOfMatches =
	[regex numberOfMatchesInString:string
		options:0
		range:NSMakeRange(0, [string length])
	];

サンプル

日付、時間を抜き出す

NSString* string = @"2012/4/13 (木) 14:43";
NSError* error = nil;
NSRegularExpression* regexp =
	[NSRegularExpression regularExpressionWithPattern:@"^(\d+/\d+/\d+).+(\d+:\d+)$"
		options:0
		error:&error
	];
if( error != nil ){
	// Error.
}
else{
	NSTextCheckingResult*	match =
		[regexp firstMatchInString:orgString
			options:0
			range:NSMakeRange(0, orgString.length)
		];
	NSString* result = [NSString stringWithFormat:@"%@ %@",
		[orgString substringWithRange:[match rangeAtIndex:1]],
		[orgString substringWithRange:[match rangeAtIndex:2]]];
}

簡易比較

BOOL foundTrue = ([strTest rangeOfString:@"true"].location != NSNotFound);

メモ

compare:options:
https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html

11
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?