【问题标题】:How to obtain a substring based on index in C如何根据C中的索引获取子字符串
【发布时间】:2015-06-30 14:14:52
【问题描述】:

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

【问题讨论】:

  • 你需要子字符串做什么?我问,因为子字符串的 C 技术取决于您是否只是暂时需要子字符串,是否应该修改,等等。
  • 我将继续操作生成的字符串。它应该能够将其复制到内存中的新位置

标签: c string char substring


【解决方案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;
}

【讨论】:

    【解决方案2】:

    应该这样做:

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

    【讨论】:

    • 他是一个 Java 男孩,一定要提到他必须在完成后释放该指针 :)
    猜你喜欢
    • 2014-04-22
    • 2016-08-28
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多