鱼C论坛

 找回密码
 立即注册
查看: 1710|回复: 2

【c++问题求助】编写一个提取子字符串的函数

[复制链接]
发表于 2022-6-6 21:02:54 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
(1)编写一个提取子字符串的函数,函数原型为 char *substr(char *s,int start,int end); *s为源字符串,start为开始位置,end为结束位置。
(2)编写函数int find(int *data,int n,int x);其功能是在data所指向的一维数组中查找值为x的元素,若找到,则函数返回该元素的下标;若找不到,则函数返回-1.其中n指定数组元素个数。编写完整的程序并测试。
求助一下大佬们
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-6-6 23:10:58 | 显示全部楼层
你确定是char *,而不是string吗?
这可是C++,你有什么理由使用char *类型?
$ ls
main.cpp
$ cat main.cpp
#include <iostream>
#include <string>

using std::string;
using std::cout, std::endl;

// [start, end)
const string substr(const string &s, size_t start, size_t end) {
    if(start > s.size()) start = s.size();
    if(end > s.size()) end = s.size();
    if(end <= start) return "";
#if 0
    return s.substr(start, end - start);
#else
    string result;
    for(size_t i = start; i < end; ++i) {
        result += s[i];
    }
    return result;
#endif
}

int find(int *data, size_t size, int x) {
    for(size_t i = 0; i < size; ++i) {
        if(data[i] == x) return i;
    }
    return -1;
}

int main() {
    cout << substr("hello world!", 3, 8) << endl;
    cout << substr("hello world!", 3, 99) << endl;
    cout << substr("hello world!", 99, 3) << endl;
    cout << substr("hello world!", 99, 99) << endl;
    cout << substr("hello world!", 8, 3) << endl;
    cout << substr("hello world!", 0, 11) << endl;
    cout << substr("hello world!", 0, 12) << endl;
    cout << substr("hello world!", 1, 11) << endl;
    cout << substr("hello world!", 1, 12) << endl;

    int data[] = {1, 9, 2, 3, 8, 6, 7, 5, 4};
    const size_t data_size = sizeof(data) / sizeof(data[0]);
    cout << find(data, data_size, 0) << endl;
    cout << find(data, data_size, -1) << endl;
    cout << find(data, data_size, -99) << endl;
    cout << find(data, data_size, 99) << endl;
    cout << find(data, data_size, 10) << endl;
    cout << find(data, data_size, 9) << endl;
    cout << find(data, data_size, 1) << endl;
    cout << find(data, data_size, 5) << endl;
    cout << find(data, data_size, 7) << endl;
    return 0;
}
$ g++-debug -o main main.cpp
$ ./main
lo wo
lo world!



hello world
hello world!
ello world
ello world!
-1
-1
-1
-1
-1
1
0
7
6
$
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-6-6 23:27:58 | 显示全部楼层
人造人 发表于 2022-6-6 23:10
你确定是char *,而不是string吗?
这可是C++,你有什么理由使用char *类型?

一道c++的题目,不用string我也很头痛
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-10-6 02:21

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表