取子串(指针)

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;
}
相关推荐
劲镝丶10 分钟前
malloc概述
c语言·开发语言·c++
艾醒10 分钟前
探索大语言模型(LLM):Open-WebUI的安装
人工智能·算法·全栈
猫天意1 小时前
【CVPR2023】奔跑而非行走:追求更高FLOPS以实现更快神经网络
人工智能·深度学习·神经网络·算法·机器学习·卷积神经网络
努力努力再努力wz1 小时前
【C++进阶系列】:万字详解红黑树(附模拟实现的源码)
java·linux·运维·c语言·开发语言·c++
cccyi71 小时前
C/C++类型转换
c++
枫fengw1 小时前
9.8 C++
开发语言·c++
宁檬精1 小时前
算法练习——55.跳跃游戏
数据结构·算法·游戏
王璐WL1 小时前
【C语言入门级教学】内存函数
c语言·开发语言·算法
啃啃大瓜1 小时前
python常量变量运算符
开发语言·python·算法
熊文豪1 小时前
【华为OD】找出通过车辆最多颜色
算法·华为od