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

标签 c string char substring

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

相关文章:

java - Java中的正则表达式匹配

python - 如何使用正则表达式删除python字符串中的特定模式?

python - 正则表达式,先查找 - Python

c - 将 char 数组初始化为 NULL 奇怪的行为

c - 如何在C中将字符串(char *)转换为大写或小写

c - 如何在单个 gcc 命令中将多个头文件包含和库目录添加到搜索路径?

c - 在循环列表中添加节点

c++ - 如何在 C/C++ 中比较两个二维 char 数组

c - 如何正确使用 memcpy 而不会出现段错误?

c - C中程序堆栈的确切内容是什么?