給定一個字符串,翻轉字符串中的每個單詞,附c語言實現

把一個字符串按照單詞反轉過來,比如 "the sky is in blue",反轉成"blue in is sky the" 


用OC的就比較簡單了,

1.先用空格切割這個字符串,

2.然後反轉數組,

3.最後在把數組用空格join起來就可以了.

- (void)viewDidLoad {
    [super viewDidLoad];

    // oc實現
    NSString * str = @"the sky is blue";
    NSArray * array = [str componentsSeparatedByString:@" "];
    NSString * result = @"";
    NSArray * resultArray = [[array reverseObjectEnumerator] allObjects];
    
    result = [resultArray componentsJoinedByString:@" "];
    NSLog(@"%@",result);
}

c語言的實現纔是重點,

1.移動到最後找出字符串的最後一個字符

2.left向前尋找單詞的邊界,如果爲' ',說明是單詞的分隔了

3.找到後left和right之間的就是一個完整的單詞,加入到result中

4.繼續2,3步,直到left==0, 這時result中的就是結果了,注意處理' '的情況

    // c語言實現
    char * str = "the sky is in blue";
    // 存放結果字符串
    char result[100] ={};
    // 這個單詞的左邊
    int left = 0;
    // 單詞的右邊
    int right = 0;
    // result數組的下表
    int resultI = 0;
    // 先找到原始字符串的最後一個char的下表
    for (int i = 0; str[i]!='\0'; i++) {
        left = right = i;
    }
    
    
    while (left >= 0) {
        // left開始左移,尋找單詞的最左邊
        while (str[left]!=' ' && left>0) {
            left--;
        }
        
        // 把這個單詞放入到result中,空格單獨處理下
        for (int i = left; i<=right; i++) {
            if (str[i] == ' ' ) {
                continue;
            }
            result[resultI] = str[i];
            resultI ++;
        }
        // 手動在後面追加空格
        result[resultI] = ' ';
        resultI++;
        
        // 找下一個單詞
        right = left;
        left --;
        
    }
    // 去掉最後一個空格
    result[resultI-1] = '\0';

    NSLog(@"%s",result);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章