[英]How to return a new string in a function in c?
您好我的 function 應該打印 str1 以 str2 開頭(如果找到),我想在下面的 function 中返回一個新字符串(newStr),但它不起作用。 請幫忙
char *myFunction(char *str1, char *str2){
int strLen;
int i;
int j;
char temp;
char *newStr;
strLen=0;
while(str1[strLen]!='\0'){
strLen++;
}
i=0;
j=0;
while(i<=strLen && str1[i]!='\0'){
if(str1[i]==str2[j] ){
newStr[i]=str1[i];
j++;
} else {
newStr[i]=str1[i];
}
i++;
}
return (newStr);
}
char *newStr
未初始化; 在為其分配任何值之前,您必須為其分配 memory。
使用malloc
或calloc
分配 memory 。
對於初學者, function 應聲明為
char * myFunction( const char *str1, const char *str2 );
因為傳遞的字符串在 function 中沒有改變。
如果 function 必須返回一個新字符串,那么您需要分配一個字符數組來存儲該字符串。 但是,您使用的是未初始化的指針newStr
char *newStr;
while循環中的條件
while(i<=strLen && str1[i]!='\0'){
沒有多大意義。
變量j
實際上沒有被使用。
while 循環中的 if-else 語句沒有意義。
如果您被允許使用標准的 C 字符串函數,那么您的 function 可以非常容易地實現。
#include <string.h>
char * myFunction( const char *s1, const char *s2 )
{
char *p = strstr( s1, s2 );
if ( p != NULL )
{
size_t n = strlen( p );
s1 = p;
p = malloc( n + 1 );
if ( p != NULL ) memcpy( p, s1, n + 1 );
}
return p;
}
否則 function 可以通過以下方式定義
char * myFunction( const char *s1, const char *s2 )
{
size_t n1 = 0;
while ( s1[n1] ) ++n1;
size_t n2 = 0;
while ( s2[n2] ) ++n2;
char *p = NULL;
if ( !( n1 < n2 ) )
{
int found = 0;
size_t i = 0;
while ( !found && i < n1 - n2 + 1 )
{
if ( s1[i] == s2[0] )
{
size_t j = 1;
while ( j < n2 && s1[i + j] == s2[j] ) ++j;
found = j == n2;
}
if ( !found ) ++i;
}
if ( found )
{
p = malloc( n1 - i + 1 );
if ( p != NULL )
{
size_t j = 0;
do
{
p[j] = s1[i + j];
} while ( p[j++] != '\0' );
}
}
}
return p;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.