取子串(指针)

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;
}
相关推荐
Zevalin爱灰灰1 天前
现代密码学 第二章——流密码【下】
算法·密码学
飞Link1 天前
大模型长文本的“救命稻草”:深度解析 TurboQuant 与 KV Cache 压缩技术
算法
郝学胜-神的一滴1 天前
深度学习优化核心:梯度下降与网络训练全解析
数据结构·人工智能·python·深度学习·算法·机器学习
Je1lyfish1 天前
CMU15-445 (2025 Fall/2026 Spring) Project#3 - QueryExecution
linux·c语言·开发语言·数据结构·数据库·c++·算法
许彰午1 天前
03-二叉树——从递归遍历到非递归实现
java·算法
Brilliantwxx1 天前
【C++】 vector(代码实现+坑点讲解)
开发语言·c++·笔记·算法
叼烟扛炮1 天前
C++第三讲:类和对象(中)
开发语言·c++·类和对象
KuaCpp1 天前
C++新特性学习
c++·学习
墨染千千秋1 天前
C/C++ Keywords
c语言·c++
ximu_polaris1 天前
设计模式(C++)-行为型模式-中介者模式
c++·设计模式·中介者模式