按字节截取字符串(HJ46)

一:解题思路

这道题目需要注意的是,一个中文字符是占2个字节的。用C/C++ 中原生的数组即可以做到按字节访问的,数组本质就是按指针运算进行的,而指针运算的本质就是按字节进行算偏移量。

二:完整代码示例 (C++版和Java版)

C++代码:

#include <iostream>
#include <string>

using namespace std;


int main()
{
    string str = "";

    while (cin >> str)
    {
        int n = 0;
        cin >> n;
        for (int i = 0; i < n; i++)
            cout << str[i];
        cout << endl;
    }

    return 0;
}

 

posted @ 2020-08-04 16:40  repinkply  阅读(267)  评论(0)    收藏  举报