-3

I have the following

char* str = "Some string";

How can I get a substring, from n to m symbols of str?

user3663882
  • 6,957
  • 10
  • 51
  • 92

5 Answers5

1

As following code:

int m = 2, n = 6;
char *p = (char *)malloc(sizeof(char) * (n - m));
for (size_t i = m; i < n; i++)
{
    p[i - m] = str[i];
}
if(p)  
    printf("Memory Allocated at: %x/n",p);  
else  
    printf("Not Enough Memory!/n");  
free(p);
TinyBox
  • 34
  • 3
1

Here is a demonstrative program that shows how the function can be written.

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

char * substr( const char *s, size_t pos, size_t n )
{
    size_t length = strlen( s );

    if ( !( pos < length ) ) return NULL;

    if ( length - pos < n ) n = length - pos;

    char *t = malloc( ( n + 1 ) * sizeof( char ) );

    if ( t )
    {
        strncpy( t, s + pos, n );
        t[n] = '\0';
    }

    return t;
}

int main(void) 
{
    char* s = "Some string";

    char *t = substr( s, 0, strlen( s ) );

    assert( strlen( s ) == strlen( t ) && strcmp( t, s ) == 0 );

    puts( t );

    free( t );

    size_t n = 5, m = 10;

    t = substr( s, n, m - n + 1 );

    assert( strlen( t ) == m - n + 1 && strcmp( t, "string" ) == 0 );

    puts( t );

    free( t );

    return 0;
}

The program output is

Some string
string
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

Try using this code

char *str = "Some string"
char temp[100];
char *ch1, *ch2;
ch1 = strchr(str,'m');
ch2 = strchr(str,'n');
len = ch2-ch1;
strncpy(temp,ch1,len);
Chintan Patel
  • 310
  • 1
  • 2
  • 11
0
char destStr[30];
int j=0;
for(i=n;i<=m;i++)
destStr[j++] = str[i];

destStr[j] = '\0';

Just copy the required characters using the loop as shown above. If you opt not to use the existing string family functions.

Gopi
  • 19,784
  • 4
  • 24
  • 36
0

You can use strscpn function. Try this

int start, end;
start = strcspn(str, "m");  // start = 2
end = strcspn(str, "n");    // end = 9
char *temp = malloc(end-start + 2);   // 9 - 2 + 1 (for 'n') + 1(for '\0')

strncpy(temp, &str[start], end-start + 1);
temp[end-start + 1] = '\0';
haccks
  • 104,019
  • 25
  • 176
  • 264