对于一些背景,我对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/