我有以下
char* str = "Some string";
如何从n
的{{1}}到m
符号获取子字符串?
答案 0 :(得分:1)
如下代码:
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);
答案 1 :(得分:1)
这是一个演示程序,显示了如何编写函数。
#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;
}
程序输出
Some string
string
答案 2 :(得分:0)
尝试使用此代码
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);
答案 3 :(得分:0)
char destStr[30];
int j=0;
for(i=n;i<=m;i++)
destStr[j++] = str[i];
destStr[j] = '\0';
只需使用循环复制所需的字符,如上所示。如果您选择不使用现有的字符串系列函数。
答案 4 :(得分:0)
您可以使用strscpn
功能。试试这个
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';