2012年10月23日

找尋 NSString 字串裡的某一個字或某一段字,將之取代為另一個字或另一段字


找尋字串裡是否含有某一個字或某一段文字,如果確定找到,將之取代為另一個字或另一段文字:

e.g.
I am in a bad mood.  ==>  I am in a good mood.
我今天心情很。  ==>   我今天心情很

*************************************************

- (void) viewDidLoad {

NSString *original = @"I am in a bad mood.";

NSLog (@"After replace, the result = %@", [self replaceStringWithSomeCharacters: original]);

}

- (NSString *) replaceStringWithSomeCharacters : (NSString *) aString{
    
 // 1. 定義要換掉的字串
    NSRange search = [aString rangeOfString:@"bad" options:NSCaseInsensitiveSearch];
  
//2. 建立一個新字串,值為 ""
    NSString *afterReplace = @"";

//3. 如果有找到要替換的"bad"
    if (search.location != NSNotFound) {

//4. 以"good" 替換掉 search 
        afterReplace = [aString stringByReplacingCharactersInRange:search withString:@"good"];

//5. 回傳替換後的結果
        return afterReplace;
    }
  
//4. 字串中找不到有"bad"的地方,回傳原來的字串
    return aString;
}

2012年10月7日

iOS -- different fonts and colors in a NSString 字串裡可以有不同的字體和顏色



讓某一個 NSString 裡可以有不同的 font 和顏色

                 



iOS 3.2 以後   iOS 6 以前  如果要達到這樣的效果,可以試一試下列的步驟:

1. 加入 CoreText.framework
2、匯入 TTTAttributedLabel.h  和  TTTAttributedLabel.m 到你的 Xcode Project
3、不要使用 UILabel; 改用 TTTAttributedLabel 的 class



QQViewController.h


#import <UIKit/UIKit.h>
#import "TTTAttributedLabel.h"

@interface QQViewController : UIViewController 
@property (strong, nonatomic) TTTAttributedLabel *label;

@end

QQViewController.m
#import "QQViewController.h"

@implementation QQViewController
@synthesize label;

- (void)viewDidLoad
{
    [super viewDidLoad];

//定義標籤框Label 的一些參數
    label = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(10, 20, 200, 100)];
    label.font = [UIFont systemFontOfSize:18];
    label.textColor = [UIColor blueColor];
    label.lineBreakMode = UILineBreakModeWordWrap;
    label.numberOfLines = 0;
    
    NSString *text = @"Lorem ipsum dolar sit amet";
    

    [label setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {

    //SET 3 different RANGES  設定一字串中有三個不同的範圍
    NSRange frontRange = [[mutableAttributedString string] rangeOfString:@"Lor" options:NSCaseInsensitiveSearch];
        
    NSRange boldRange = [[mutableAttributedString string] rangeOfString:@"ipsum dolar" options:
            NSCaseInsensitiveSearch];

    NSRange aStressRange = NSMakeRange(24, 1);

        //SET FONT 設定字體
        //粗體
        UIFont *boldSystemFont = [UIFont boldSystemFontOfSize:18];
        CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)boldSystemFont.fontName, boldSystemFont.pointSize, NULL);
        //斜體
        UIFont *italicSystemFont = [UIFont italicSystemFontOfSize:18];
        CTFontRef italicFont = CTFontCreateWithName((__bridge CFStringRef)italicSystemFont.fontName, italicSystemFont.pointSize, NULL);
        
        if (font) {
            //第一段範圍的字體
            [mutableAttributedString removeAttribute:(NSString *)kCTFontAttributeName 
              range:frontRange];//prevent memory leak
            [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:
              (__bridge id)italicFont range:frontRange];
            
            //第二段範圍的字體
            [mutableAttributedString removeAttribute:(NSString *)kCTFontAttributeName 
              range:boldRange];//prevent memory leak
            [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:
            (__bridge id)font range:boldRange];
           
            //第三段範圍的字體
            [mutableAttributedString removeAttribute:(NSString *)kCTFontAttributeName 
              range:aStressRange];//prevent memory leak
            [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:
            (__bridge id)font range:aStressRange];
            
            //自定字體
            // [mutableAttributedString addAttribute:@"TTTCustomStrikeOut" value:[NSNumber
            //  numberWithBool:YES] range:aStressRange];
            
            CFRelease(font);
        }  //end of font

        
       //SET COLOR
        //第一段範圍的字體顏色
        [mutableAttributedString addAttribute:(NSString *) kCTForegroundColorAttributeName 
          value:(id)[[UIColor greenColor] CGColor] range:frontRange];


        //第二段範圍的字體顏色
         [mutableAttributedString addAttribute:(NSString*)kCTForegroundColorAttributeName 
          value:(id)[[UIColor grayColor] CGColor] range:boldRange];
        
         //第三段範圍的字體顏色
        [mutableAttributedString addAttribute:(NSString *) kCTForegroundColorAttributeName 
          value:(id) [[UIColor redColor] CGColor] range:aStressRange];
        
        
        //SET CAPITAL
        [mutableAttributedString replaceCharactersInRange:boldRange withString:
          [[[mutableAttributedString string] substringWithRange:boldRange] uppercaseString]];
        
        return mutableAttributedString;
    }];
    
    [self.view addSubview:label];
    
    
    
}






iOS --.xlsx 檔轉成 .csv 檔,準備之後轉成 sqlite檔使用

以 mac 的作業系統為例:
將 excel 的 .xlsx 檔轉成 .csv 的步驟:

1. 建立一個 .xlsx 檔

 
 
 2. 另存成 .csv 檔

 3. 以 text 瀏覽器打開,在此我使用 TextWrangler 。到 Edit --> Document Options:
     
             
 4. 將它 copy 入 Xcode 的 project 裡以用建立 sqlite 檔使用。
     要確定 .csv 檔在 project 裡沒問題,可以點它,看中文有無亂碼:
     如果見到如下,就沒問題:

     學生;國文;英文
     John;89;90
     Mary;56;83
     Peter;78;54


*PS 在 .xlsx 裡輸入資料時,請不要用英文的分號 (;)。如果真的需要分號,請以中文的方式輸入(;)。這樣才能確保在程式裡轉檔成sqlite檔案時不會出問題!!!

 
 


iOS -- sqlite3 的使用順序 & query 例子



使用 sqlite3 的一般步驟:


sqlite3_open()        Open the database  打開資料庫
sqlite3_prepare()     Create the SQL statement  準備建立好的資料庫指令 (query)
sqlite3_step()        Execute the statement  執行指令
sqlite3_column()      Fetch the result  取得結果
sqlite3_finalize()    Destroy the statement  銷燬指令
sqlite3_close()       Close the database  關閉資料庫


query 例子:
1. CREATE  TABLE "main"."STARS" ("Rowid" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  UNIQUE , "Star" VARCHAR, "image" BLOB)


2. SELECT DISTINCT [column_name] FROM [table_name];

3. SELECT * FROM * WHERE * LIKE %$value%;

4. 找幾筆資料 (no. of rows in the table):
NSString *query = [NSString stringWithFormat:@"SELECT COUNT(%@) FROM %@ ", kSelectedColumn, kTablename];
    sqlite3_stmt *stmt;
    if (sqlite3_prepare_v2(database, [query UTF8String] , -1, &stmt, nil) == SQLITE_OK) {
     
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            int noOfRows = (int) sqlite3_column_int(stmt, 0);
            NSLog(@"%d", noOfRows);
        }
        sqlite3_finalize(stmt2);
    } else NSLog(@"never entered!!!");
    sqlite3_close(database);



Fetch 的例子:

int sqlite3_column_count(sqlite3_stmt *pStmt);


可參考:http://www.sqlite.org/capi3ref.html

iOS -- NSString 轉 C string and vise versa



// 從 NSString 轉成 char (C 語言物件:C string):

   NSString *aStr = @"Hello CQ!";
   const char *update = [aStr cStringUsingEncoding:NSUTF8StringEncoding];
   printf("%s\n",  update);

或是:

e.g. 1
const char *ptr2 = [aStr UTF8String];
printf("%s\n", ptr2);



e.g. 2 (適用在建立 sqlite3 的query)

NSString *query = [NSString stringWithFormat:@"SELECT %@ FROM %@ WHERE %@ = %@ ORDER BY %@, destinationColumn, aTablename, aColumn, aString, ROWID";
    const char * sql = [query UTF8String];


********************************

// C string 轉  NSString

ptr = "C string to string object";
NSString *str = [NSString stringWithCString:ptr encoding:NSUTF8StringEncoding];
NSLog(@"%@", str);