取子串(指针)

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;
}
相关推荐
洛水水2 小时前
【力扣100题】58.轮转数组
算法·leetcode
资深流水灯工程师2 小时前
LMS 最小均方算法在 DSP 上的 C 语言实现
算法
风筝在晴天搁浅2 小时前
阿里 LeetCode 876.链表的中间节点
算法·leetcode·链表
玖釉-2 小时前
二叉树展开为链表:从先序遍历到原地指针重排
c++·windows·算法·leetcode·链表
05候补工程师2 小时前
【408考研·数据结构专题】二叉树、树与森林、线索树及哈夫曼树核心考点与秒杀技巧深度总结
数据结构·经验分享·笔记·考研·算法
吃好睡好便好2 小时前
矩阵的加减运算
开发语言·人工智能·学习·线性代数·算法·matlab·矩阵
吃好睡好便好3 小时前
提取矩阵特定多行元素
开发语言·线性代数·算法·matlab·矩阵
Mister西泽3 小时前
C++ Primer Plus 第六版 编程练习题及详细答案
开发语言·c++·学习·visual studio
葫三生3 小时前
多模态视角下的一部当代东方创世史诗 ——《论三生原理》?(扩版)
人工智能·科技·算法·机器学习·开源
Qt程序员3 小时前
从上电到系统就绪:ARM+U-Boot 嵌入式 Linux 启动流程
linux·运维·c++·内核·设备树·嵌入式·ram