如何根据C

时间:2015-04-22 18:13:19

标签: c string char substring

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

出于我的实现目的,我只会关闭第一个char并返回剩余的String。这是我在java中的实现。

public String cut_string(String word)
{

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

2 个答案:

答案 0 :(得分:1)

使用类似的东西

#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;
}

答案 1 :(得分:-1)

这应该这样做:

char* cut_string(char const* in)
{
   // Compute the length of the input string and use
   // that length to allocate memory for the string to
   // be returned.
   // strlen(in) returns the length of the string.
   // malloc(...) allocates memory.
   char* ret = malloc(strlen(in));
   if ( ret == NULL )
   {
      // If there is a problem in allocating memory
      // return NULL. We can't do anything about 
      // cutting the input string.
      return NULL;
   }

   // Copy the input string to the string to be returned.
   // Start copying from the second character. If
   // in is "This is a string", in+1 is "his is a string".
   strcpy(ret, in+1);

   // Return the resulting string.
   return ret;
}

在调用函数中,

char* s = cut_string("my string");
if ( s != NULL )
{
   // Use s

   // Make sure to free the memory returned by cut_string.
   free(s);
}