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);





2012年6月28日

如何在iOS讀出繁體中文的檔案


如何在iOS讀出繁體中文的檔案:

準備兩個檔;一個是以Big5寫的, e.g. translation01.txt
                     另一個是以UTF-8寫的,e.g. UTF8.txt





#import <Foundation/Foundation.h>

/** 讀出中文檔案內容 **/

int main (int argc, const char * argv[])
{

    @autoreleasepool {
        
        NSLog(@"** begin **");
        NSString * strBig5, *strUTF8, *strUTF_8;
               
        //Big5
        NSLog(@"\n\n** 這是繁體中文Big5的實驗 **");
         NSStringEncoding encBig5 = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingBig5);
        strBig5 = [[NSString alloc] initWithContentsOfFile:@"/Users/apple/Desktop/Android/Resources/txt/translation01.txt" encoding:encBig5 error:nil];//OK
         NSLog(@"%@\n\n", strBig5);
        
        
        //UTF─8
        NSLog(@"** 這是繁體中文UTF-8的實驗 **");
        strUTF_8 = [[NSString alloc] initWithContentsOfFile:@"/Users/apple/Desktop/Android/Resources/txt/UTF8.txt" encoding:NSUTF8StringEncoding error:nil];
        NSLog(@"%@\n\n", strUTF_8);
        
        
        //UTF8:舊式
        NSLog(@"** 這是UTF8的實驗(舊式) **");
         NSStringEncoding encUTF8 = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF8);
        strUTF8 = [[NSString alloc] initWithContentsOfFile:@"/Users/apple/Desktop/Android/Resources/txt/UTF8.txt" encoding:encUTF8 error:nil];
        NSLog(@"%@", strUTF8);
        
        
       
    }
    
    return 0;
}

結果:


2012-06-28 22:51:53.146 InitiationChap10[912:903] ** begin **
2012-06-28 22:51:53.150 InitiationChap10[912:903] 
** 這是繁體中文Big5的實驗 **
2012-06-28 22:51:53.160 InitiationChap10[912:903] 1.她是像天使般的女性。
She is an angel of a woman.
2.排山巨浪湧過來了。
A mountain of a wave came near.
3.這幾乎是不可能的。
This is all but impossible.
4.她就像是死了一樣。
She is all but dead.
5.他們並非全部都滿意這項結果。
All of them were not satisfied with the result.
2012-06-28 22:51:53.161 InitiationChap10[912:903] ** 這是繁體中文UTF-8的實驗 **
2012-06-28 22:51:53.162 InitiationChap10[912:903] 這是utf8的實驗,希望能顯示繁體中文。
2012-06-28 22:51:53.164 InitiationChap10[912:903] ** 這是UTF8的實驗(舊式) **
2012-06-28 22:51:53.165 InitiationChap10[912:903] 這是utf8的實驗,希望能顯示繁體中文。
Program ended with exit code: 0



P.S.
簡體中文的話,得改成:kCFStringEncodingGB_18030_2000

2012年5月31日

網路檔案下載─FTP



網路檔案下載─FTP: 從中華電信提供的網路存放空間,下載檔案。

使用外部元件: Apache Commons NET
   commons-net-3.0.1-src.zip 的class : 下載點

     1. Unzip it.
     2. 到Eclipse的android作業平台上的 File -> Import -> General -> File System
    

          

       3. 然後 Browse 剛才Unzip後 存放 commons-net-3.0.1-src 的夾子,找到 java 的子目錄,然後按『確定』。

4. 你的作業環境,應該會呈現下圖的樣子,如果如圖所示,表示成功,便可以開始使用了。





需開啟之權限: 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>


main.java


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.http.util.EncodingUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

public class FTPDownloadFileActivity extends Activity {
    /** Called when the activity is first created. */

private TextView tv;
private TextView tvContent;
private String fileName = "myFile.txt"; //網站上準備要下載的檔名


private final String SD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
private final String FILE_PATH = "/download";
private final String FILE_NAME = "copy_" + fileName; //下載進手機後的檔名
private final String ENCODING = "UTF-8";
private FileInputStream fis = null;


        private ProgressDialog mProgressDialog;
 
private Handler handler = new Handler(){  //使用handler, thread 防止下載檔案太大

@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
mProgressDialog.dismiss(); //close
readFile();
}

};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        tv = (TextView)findViewById(R.id.textview);
        tvContent = (TextView) findViewById(R.id.textviewContent);
        processThread();
     
    }
 
 
 
    private void ftpDownload() {  //使用FTP 下載檔案
    FTPClient ftpClient = new FTPClient();
    try {
//     ftpClient.connect(InetAddress.getByName("203.66.87.21"));//與以下的String 意義一樣
    ftpClient.connect(InetAddress.getByName("ftp.myweb.hinet.net")); //中華電信的網頁IP ADDRESS
    ftpClient.login("username", "password");
    tv.setText(String.valueOf(ftpClient.isConnected()));
    ftpClient.changeWorkingDirectory("/");
    File localfile = new File ("/sdcard/download/" + FILE_NAME);
    OutputStream os = new FileOutputStream(localfile);
    ftpClient.enterLocalPassiveMode();
    ftpClient.retrieveFile(fileName, os);
    ftpClient.logout();
    ftpClient.disconnect();
    }catch (Exception e) {
    e.printStackTrace();
    }
    }
 
 
    public void readFile () {  //將內容顯示到螢幕上
     
        String result = "";
        try {
       
         File mFilePath = new File (SD_PATH + FILE_PATH);
         String mFileName = mFilePath + "/" + FILE_NAME;
         File fileText = new File (mFileName);
       
         fis = new FileInputStream(fileText);
         int length = fis.available();
         byte [] buffer = new byte [length];
         fis.read(buffer);
         result = EncodingUtils.getString(buffer, ENCODING);
         fis.close();
         tvContent.setText(result);
       
        } catch (Exception e) {
         e.printStackTrace();
        }
       }
 
 
    private void processThread() {
    mProgressDialog = ProgressDialog.show(this, "文件下載", "正在下載...");
    new Thread () {

@Override
public void run() {
// TODO Auto-generated method stub
//super.run();
ftpDownload();
prolongedActionMethod(); //做測試用的
handler.sendEmptyMessage(0);
}
   
    }.start();
    }
 
 
    private void prolongedActionMethod() { //故意延遲十秒鐘,做測試用的
    try {
    Thread.sleep(10000);
    }catch (Exception e){
    e.printStackTrace();
    }
    }
}


*************************************************
res/layout/main.xml:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        />
    <!--  將 TextView 包在 ScrollView 裡,當內容太長,可以捲動。  -->
     <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:fadingEdge="vertical"
        android:paddingTop="10dip"
        android:scrollbars="vertical" >

        <TextView
            android:id="@+id/textviewContent"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="10dip"
            android:text=""
            android:textSize="20dp"
            android:textColor="#00FF00" />
    </ScrollView>

</LinearLayout>