[Title] Huawei machine test 108 byte string interception

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/u011544909/article/details/79944468

Title Description
write a function string taken, and the number of the input as a string of bytes, the output is taken byte string. However, to ensure that characters will not be cut half, such as "My ABC" 4, should be cut as "I AB", enter "ABC me Han DEF" 6, the output should be "My ABC" instead of "I'm half Chinese and ABC + . "

Description Input:
Input string and the length to be taken

: Description output
string taken after

Example 1
Input
I Han ABC DEF
6
output
my ABC


The general idea of ​​determining the n-th bit string str is greater than 128 to know whether the previous byte characters.

#include <iostream>
#include <string>
using namespace std;
int main(){
    string s;
    int N;
    while(cin>>s>>N){
        string ss;
        if(s[N-1]>=128)//判断尾字符是否是汉字的前一个字节
            ss=s.substr(0,N-1);
        else
            ss=s.substr(0,N);
        cout<<ss<<endl;   
    }
    return 0;
}

Indeed, string type carrying this feature, the above-described program can be rewritten as:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    string str;
    int n;
    while(cin>>str>>n)
    {
        string temp;
        temp =str.substr(0,n);
        cout<<temp<<endl;
    }

    return 0;
}

Guess you like

Origin blog.csdn.net/u011544909/article/details/79944468