取子串(指针)

cpp 复制代码
#include <stdio.h>
#include <string.h>

char* substr(char *s, int startloc, int len) {
    static char result[51]; // 定义一个足够大的静态数组来存储结果
    static char result1[] = {'N','U','L','L','\0'};
    int i, j;

    // 检查startloc是否在字符串的范围内
    if (startloc < 1 || startloc > strlen(s)) {
        return result1; // 如果不在范围内,返回NULL
    }

    // 计算实际要复制的子串长度
    int actual_len = (startloc + len-1 < strlen(s)) ? len : (strlen(s) - startloc+1);

    // 复制子串到结果数组
    for (i = startloc-1, j = 0; i < startloc + actual_len-1; i++, j++) {
        result[j] = s[i];
    }
    result[j] = '\0'; // 添加字符串结束符

    return result; // 返回结果
}

int main() {
	int t;
	scanf("%d",&t);
	while(t--)
	{
		char a[100];
		scanf("%s",a);
		int x,y;
		scanf("%d %d",&x,&y);
		printf("%s\n", substr(a, x, y));
	}

    return 0;
}
相关推荐
saltymilk10 小时前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程
感哥10 小时前
C++ lambda 匿名函数
c++
沐怡旸16 小时前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥17 小时前
C++ 内存管理
c++
聚客AI17 小时前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
大怪v19 小时前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
惯导马工21 小时前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
骑自行车的码农1 天前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了1 天前
AcWing学习——双指针算法
c++·算法
感哥1 天前
C++ 指针和引用
c++