字符串中的malloc更换字符 [英] Replacing characters in strings malloc
问题描述
给定一个字符串,两个字符,我想找到的第一个字符多少次存在于字符串,它第一次出现在什么位置,并创建一个新的字符串,其中第二个字符替换每次显示时间第一,但我在与最后一部分的问题。这是我到目前为止有:
Given a string and two characters, I want to find how many times the first character exists on the string, in what position it appears first and create a new string where the second character replaces the first every time it shows up, but I'm having problems with the last part. This is what I have so far:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
main ()
{
char string[10], string1;
char c1, c2;
int contador, i, l, n, contador2;
printf ("Introduza uma string e dois caracteres.\n");
scanf ("%s %c %c", string, &c1, &c2);
l = strlen (string);
contador = 0;
for (n = 0; n < l; n++)
{
if (c1 == string[n])
{
contador = contador + 1;
}
}
for (n = 0; n < l; n++)
{
if (c1 == string[n])
{
contador2 = n + 1; /*Dá-se o valor de n + 1 à variável contador2 porque n começa em 0*/
break;
}
}
string1 = (char) malloc ((l +1)*sizeof(char));
for (n = 0; n < l; n++)
{
if (c1 == string1[n])
{
n = c2;
}
}
printf ("%d\n", contador);
printf ("%d\n", contador2);
printf ("%s", string1);
}
我想AP preciate你关心提供任何帮助。
I'd appreciate any help you'd care to offer.
推荐答案
您字符串1
的声明是错误的。它不应该是一个字符
而是一个指向字符
,的char *
。然后,你也不会动心投的返回值的malloc
。
Your declaration of string1
is wrong. It shouldn't be a char
but a pointer to char
, char*
. Then you also wouldn't be tempted to cast the return value of malloc
.
一些小提示:
- 请不要在一个行,如果它们的类型是不同的声明几个变量,尤其如此。
- 将定义
的sizeof(char)的
是1
和的malloc
计算它的字符
数分配的大小。 - 缩进你的code正确。它不仅使别人更易读,你也将AP preciate它自己,如果你以后再次访问您的code。
- Don't declare several variables in one line, in particular if their types are different.
- By definition
sizeof(char)
is1
andmalloc
counts the size it allocates in the number ofchar
. - Indent your code properly. Not only it makes it more readable for others, also you will appreciate it yourself if you revisit your code later.
这篇关于字符串中的malloc更换字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!