gpt4 book ai didi

c - C中如何根据索引获取子字符串

转载 作者:行者123 更新时间:2023-11-30 17:16:01 25 4
gpt4 key购买 nike

对于一些背景,我对C不太熟悉,但我对Java非常精通。在我正在开发的当前程序中,我试图弄清楚如何实现与 java 方法 someString.substring(int startIndex, int endIndex) 完全相同的东西,该方法返回一个基于前一个的开始和结束索引。

出于实现目的,我只会删除第一个字符并返回剩余的字符串。这是我在 java 中的实现。

public String cut_string(String word)
{

String temp = word.substring(1, word.length());
return temp;
}

最佳答案

使用类似的东西

#include <stdio.h>
#include <stdlib.h>

char* substring(char*, int, int);

int main()
{
char string[100], *pointer;
int position, length;

printf("Input a string\n");
gets(string);

printf("Enter the position and length of substring\n");
scanf("%d%d",&position, &length);

pointer = substring( string, position, length);

printf("Required substring is \"%s\"\n", pointer);

free(pointer);

return 0;
}

/*C substring function: It returns a pointer to the substring */

char *substring(char *string, int position, int length)
{
char *pointer;
int c;

pointer = malloc(length+1);

if (pointer == NULL)
{
printf("Unable to allocate memory.\n");
exit(1);
}

for (c = 0 ; c < length ; c++)
{
*(pointer+c) = *(string+position-1);
string++;
}

*(pointer+c) = '\0';

return pointer;
}

关于c - C中如何根据索引获取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29805742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com