取子串(指针)

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;
}
相关推荐
倒头就睡的小比特3 天前
算法竞赛C++常用的STL
c++·算法
weilx12343 天前
C++笔记-文件IO-<fcntl.h>
c++
小羊没烦恼!3 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
猎头南楼3 天前
知识社区推荐系统实践:新用户冷启动与长短期兴趣建模的挑战 资深推荐算法工程师
人工智能·深度学习·算法·机器学习
Smileyqp沛沛3 天前
前端?C++ ?较大差异基础罗列
c++·基础·前端转c++
m0_547486663 天前
《数据结构教程》全套 PPT课件2026
数据结构
C语言小火车3 天前
C/C++ 为什么需要编译器?
开发语言·c++
旖旎夜光3 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
wzdark3 天前
大规模并行计算中的负载均衡算法研究4
算法
吞下星星的少年·-·3 天前
C++ 萌新语法入门篇
c++·算法比赛