我想寫一個 C 程式,它回傳一個分配在堆上的新字串。該字串是通過將字串中所有出現的“c”加倍獲得的(“abcdc”在加倍“c”后變為“abccdcc”)。
這是我的代碼,我真的不知道問題出在哪里來解決它!
size_t taille = stringLength(str);
size_t k=0;
size_t q=0;
while (*str!='\0')
{
if (*str == c)
{
k=k 1;
}
str;
}
char *nouvelle=malloc(taille 1 k);
int i,j= 0;
while(*str !='\0')
{
if (str[i] != c)
{
j=i;
nouvelle[j]=str[i];
}
else
{
j=i;
q;
nouvelle[j]=str[i];
j=i q;
nouvelle[j ]=str[i];
}
i;
}
nouvelle[taille 1 k]='\0';
return nouvelle;
}
uj5u.com熱心網友回復:
您的代碼有兩個問題。
第一個是在這個 while 回圈之后
while (*str!='\0')
{
if (*str == c)
{
k=k 1;
}
str;
}
指標str指向字串的末尾,即終止零字符'\0'。
第二個是您正在使用未初始化的變數i
int i,j= 0;
while(*str !='\0')
{
if (str[i] != c)
{
j=i;
//..
本宣告
int i,j= 0;
不一樣
int i = 0,j= 0;
即只有變數 j 被初始化為 0。
和宣告
j = i;
沒有意義。
也不清楚是c表示變數還是字符'c'。如果你的意思是這個角色'c',那么你至少需要寫成
if (*str == 'c')
您可以通過以下方式定義功能,例如下面的演示程式所示。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * duplicate_char( const char *s, char c )
{
size_t n = 0;
for (const char *p = s; *p; p)
{
if (*p == c) n;
}
char *nouvelle = malloc( strlen( s ) n 1 );
if (nouvelle)
{
if (n == 0)
{
strcpy( nouvelle, s );
}
else
{
char *p = nouvelle;
while (*s)
{
*p = *s ;
if (p[-1] == c) *p = c;
}
*p = '\0';
}
}
return nouvelle;
}
int main( void )
{
char *nouvelle = duplicate_char( "abcdc", 'c' );
if (nouvelle != NULL) puts( nouvelle );
free( nouvelle );
}
程式輸出是
abccdcc
如果你想使用你自己的函式stringLength而不是標準的 C 函式strlen那么它看起來像
size_t stringLength( const char *s )
{
const char *p = s;
while ( *p ) p;
return p - s;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/534152.html
上一篇:C函式回傳值最佳實踐
