[英]Function in C to add <SPACE> after every non space character in a string
这就是我想要做的工作
#include <stdio.h>
#include <stdlib.h>
char * xspace(char *s)
{
int i = 0, j = 0, n = strlen (s);
char final_string[n];
for (i; s[i] != '\0'; i++)
{
final_string[j] = s[i];
if(s[i] != ' ')
{
final_string[j + 1] = ' ';
}
j++;
}
final_string[j] = '\0';
return final_string;
}
int main()
{
char str[100], final_string[200];
printf("Enter a string: \n");
fgets(str, 100, stdin);
xspace(str);
printf("\n%s\n", final_string);
}
我在尝试运行它时得到的只是随机符号,我无法确定是什么原因造成的。 任何帮助表示赞赏
你可以这样做:
#include <stdio.h>
#include <stdlib.h>
char* xspace(char* s)
{
int i = 0, j = 0;
const int n = strlen(s);
// maximum size of this string can be 2*n
char* final_string= malloc(2 * n);
// add extra spaces
for (i; s[i] != '\0'; i++)
{
final_string[j] = s[i];
if (s[i] != ' ')
{
final_string[++j] = ' ';
}
j++;
}
final_string[j] = '\0';
return final_string;
}
int main()
{
char str[100];
printf("Enter a string: \n");
fgets(str, 100, stdin);
// get final string
char* final_string = xspace(str);
// print final string
printf("\n%s\n", final_string);
return 0;
}
你的问题就在这里(嗯,还有更多的问题,但是你所说的出现乱码的问题)
int main()
{
char str[100], final_string[200];
变量final_string
在这里声明,没有初始化。
printf("Enter a string: \n");
fgets(str, 100, stdin);
xspace(str);
它不在任何地方使用,因此您不会将其初始化为任何可用的东西。
printf("\n%s\n", final_string);
最后你在这里打印它,只是证明未初始化的局部变量存储垃圾。
}
除此之外,为了使您的xspaces
function 工作,我至少会再传递两个 arguments 以指示您要使用复制的字符串填充的字符串以及该缓冲区的大小,因此 w 不会缓冲区溢出它写的时候。
我的版本比你的短,这里是:
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
/* macro used in formatting error messages (see ERR macro below) */
#define F(_fmt) "%s:%d:%s:"_fmt,__FILE__,__LINE__,__func__
/* pretty printing error function. It exits if _code != 0 with
* that error code */
#define ERR(_code, _fmt, ...) do { \
fprintf(stderr, F(_fmt),##__VA_ARGS__); \
if (_code) exit(_code); \
} while(0)
/* macro to check, emit an error message and exit if not enough
* capacity to add N more characters to buffer */
#define CHK_CAP(N) do{ \
if (cap < (N)) { \
ERR(EXIT_FAILURE, \
"not enough space in bu" \
"ffer(%zd) to store" \
" result\n", initial_cap); \
} \
}while(0)
char * /* return the converted string */
xspaces(char* src, /* source string */
char *initial_buff, /* buffer to fill with the return string */
size_t initial_cap) /* buffer capacity */
{
char *tgt = initial_buff;
size_t cap = initial_cap;
for (; *src; src++) {
bool is_space = isspace(*src);
CHK_CAP(is_space ? 2 : 3); /* this counts for the final \0 */
*tgt++ = *src; /* output the char */
if (!is_space) *tgt++ = ' '; /* the space */
}
/* finish the string */
CHK_CAP(1);
*tgt++ = '\0';
return initial_buff;
}
int main()
{
char str[100], str_out[200];
printf("Enter a string: \n");
fgets(str, sizeof str, stdin);
// print final string
printf("\n%s\n",
xspaces(str, str_out, sizeof str_out));
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.