取子串(指针)

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;
}
相关推荐
~|Bernard|18 分钟前
二.go语言中map的底层原理(2026-5-8)
算法·golang·哈希算法
AbandonForce26 分钟前
哈希表(HashTable,散列表)个人理解
开发语言·数据结构·c++·散列表
mask哥31 分钟前
力扣算法java实现汇总整理(下)
java·算法·leetcode
代码中介商32 分钟前
栈结构完全指南:顺序栈实现精讲
c语言·开发语言·数据结构
样例过了就是过了1 小时前
LeetCode热题100 编辑距离
数据结构·c++·算法·leetcode·动态规划
z200509301 小时前
C++中位图和布隆过滤器的一些面试题
开发语言·c++
wearegogog1231 小时前
MATLAB椭圆参数检测算法实现
数据库·算法·matlab
secondyoung1 小时前
Markdown数学公式语法速查手册
算法·编辑器·markdown·latex
君义_noip1 小时前
CSP-S 2025 提高级 第一轮(初赛) 阅读程序(1)
算法·深度优先·信息学奥赛·初赛
小O的算法实验室1 小时前
2026年IEEE TEVC,知识引导的竞争进化算法用于多解传感器-武器-目标分配问题,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进