文字列を操作する1

| コメント(0) | トラックバック(0)

「一般的文字列の操作」

「Window-Based-Application」テンプレートから制作。
結果を確認するため、「Interface Builder」のメインウィンドウに「Library」から「Label」を配置。文字列の長さによっては、「Interface Builder」で「Label」の「width」や「font size」などの属性を変更しないと、結果がすべて見えないかもしれない。
インターフェースファイル(*.h)で「UILabelクラス」のインスンス変数、プロパティ変数を宣言し、「Interface Builder」で配置した「Label」と接続する。

【サンプル】
プロジェクト名:StringMethod

StringMethodAppDelegete.h

#import <UIKit/UIKit.h>

@interface StringMethodAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    UILabel *myLabel;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UILabel *myLabel;

@end
 

StringMethodAppDelegete.m

@synthesize window;
@synthesize myLabel;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {   
   
    //文字列を作成(NSStringインスタンスを生成)
    NSString *txt=@"ayabin-iPhone Programing";
   
    //文字列の長さを取得
    NSInteger length=[txt length];
    NSString *txtLength=[NSString stringWithFormat:@"%d",length];//NSString型にキャスト
    //【結果】24
   
    //指定した文字列を検索し、文字列が最初に現れたインデックス番号を返す
    NSRange range=[txt rangeOfString:@"iPhone"];
    NSString *txtRange=[NSString stringWithFormat:@"%d",range];//NSString型にキャスト
    //【結果】7
   
    //指定した文字列を置換して新しい文字列を作成
    NSString *newtxt=[txt stringByReplacingOccurrencesOfString:@"ayabin" withString:@"webmaster"];
    //【結果】「webmaster-iPhone Programing」
   
    //指定したインデックス番号以降の文字列を切り出す
    NSString *substrtxt=[txt substringFromIndex:7];
    //【結果】「iPhone Programing」
   
    //指定したインデックス番号よりも前にある文字列を切り出す
    NSString *substrtxt2=[txt substringToIndex:7];
    //【結果】「ayabin-」
   
    //範囲を指定して文字列を取り出す
    NSString *substrtxt3=[txt substringWithRange:NSMakeRange(7,6)];
    //NSMakeRange(スタートインデックス,切り出す文字数)
    //【結果】「iPhone」
   
    //ラベルに結果を表示
    myLabel.text=substrtxt3;
   
    [window makeKeyAndVisible];
   
    return YES;
}
 

トラックバック(0)

トラックバックURL: http://www.ayabin.jp/mt5/mt-tb.cgi/60

コメントする

このブログ記事について

このページは、webmasterが2010年7月31日 22:14に書いたブログ記事です。

ひとつ前のブログ記事は「PDFを表示する」です。

次のブログ記事は「文字列を操作する2」です。

最近のコンテンツはインデックスページで見られます。過去に書かれたものはアーカイブのページで見られます。