取子串(指针)

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;
}
相关推荐
海梨花4 分钟前
【力扣Hot100】刷题日记
算法·leetcode·1024程序员节
m0_7482402524 分钟前
基于Reactor模式的高性能C++仿Muduo库:Server服务器模块实现
服务器·c++·php
hope_wisdom26 分钟前
C/C++数据结构之用链表实现栈
c语言·数据结构·c++·链表·
DuHz32 分钟前
使用稀疏采样方法减轻汽车雷达干扰——论文阅读
论文阅读·算法·汽车·信息与通信·信号处理
王老师青少年编程37 分钟前
AtCoder真题及详细题解 ABC427C: Bipartize
c++·题解·1024程序员节·atcoder·csp·abc·信奥赛
ceclar12339 分钟前
C++容器forward_list
开发语言·c++·list
ceclar12342 分钟前
C++容器list
java·c++·list
大肘子咒你1 小时前
数字狂潮来袭
数据结构·c++·1024程序员节
hansang_IR1 小时前
【算法速成课 3】康托展开(Cantor Expansion)/ 题解 P3014 [USACO11FEB] Cow Line S
c++·算法·状态压缩·康托展开·排列映射
m0_748233641 小时前
【类与对象(中)】C++类默认成员函数全解析
开发语言·c++·算法