算法-字符串的初级处理

初级处理的功能有
递归求字符串的长度
求字符串最后一个单词的长度(有无长度)

//
//  t07_.cpp
//  C++PLUS
//
//  Created by mac on 2019/12/15.
//  Copyright © 2019 mac. All rights reserved.
//

#include 
#include
using namespace std;
int GetCharLength(char * str){
     
    if(str[0] == '\0'){
     
        return 0;
    }
    else{
     
        return GetCharLength(str+1) + 1;
    }
}
int LastWordLength(char * str,int strLength){
     
    int index = strLength-1;
    int count = 0;
    while(str[index] != ' '){
     
        count ++;
        index --;
    }
    return count;
}
int LastWordLength(char * str){
     
    int res = 0;
    int index = 0;
    while(str[index] != '\0'){
     
        if(str[index] == ' '){
     
            res = 0;
        }
        else{
     
            res = res + 1;
        }
        index ++;
    }
    return res;
}
int main(){
     
    char a[] = "Happy EveryDay!";
    cout<<"字符串长度: "<<GetCharLength(a)<<endl;
    cout<<"最后一个单词的长度: "<<LastWordLength(a)<<endl;
    cout<<"最后一个单词的长度: "<<LastWordLength(a, GetCharLength(a))<<endl;
    return 0;
}

测试效果:
算法-字符串的初级处理_第1张图片

你可能感兴趣的:(C/C++,算法)