我希望在标点符号之前将HTML字符串标记插入另一个字符串。 即鉴于“罗伯特:”,我想输出“罗伯特:”
目前我有(除了一个功能):
#define fhighlight "<font_color="red"><b>"
#define bhighlight "</b></font>"
#define punct ".,;:!?"
#define wordlen 15
char w[wordlen];
w = "Robert:";
w = strcat(fhighlight,w);
if ((strchr(punct,w)==1) { /*check for punctuation in w*/
/*not quite sure what to put here*/
} else {
w = strcat(w,bhighlight);
}
非常感谢任何帮助。
答案 0 :(得分:0)
我想你的程序中存在分段错误。看看代码的这个片段:
char w[wordlen];
w = "Robert:";
w = strcat(fhighlight,w);
你将w分配给为“Robert:”保留的内存中的已分配空间,然后你用它来制作一个strcat,这确实也是不正确的,因为你正在做类似的事情:
w = strcat("<font_color="red"><b>",w);
这将引发分段错误。我建议你重新开始新鲜的。再次编写程序并正确使用内存。
答案 1 :(得分:0)
strchr()一次只查找一个字符(并且你没有正确调用它),因此需要在punct中为每个字符循环调用。这是一个查找其中任何一个的函数。此外,您没有正确使用strcat()。
#include <string.h>
#include <stdio.h>
int char_position(const char *string,const char *chars)
{
int length = strlen(string);
while (*chars)
{
for (int i = 0; i < length; i++)
{
if ( string[i] == *chars )
{
return i;
}
}
chars++;
}
return -1;
}
const char *highlight(const char *word)
{
#define fhighlight "<font_color=\"red\"><b>"
#define bhighlight "</b></font>"
#define punct ".,;:!?"
#define wordlen 1500
static char w[wordlen];
strcpy(w,fhighlight);
int position = char_position(word,punct);
if ( position != -1 )
{
strncat(w,word,position);
strcat(w,bhighlight);
strcat(w,&word[position]);
} else {
strcat(w,word);
strcat(w,bhighlight);
}
return w;
}
int main(void)
{
printf("%s\n",highlight("Robert:"));
printf("%s\n",highlight("Roberta"));
printf("%s\n",highlight("LaDonna! is coming"));
}