删除字符串后的空格(指针)
我有一个包含姓名、姓氏、地址的结构列表...所有内容都以单独的 CHAR 字符串输入。 问题是,每当我粘贴这些字符串之一时,我也会得到一大堆空白。 例如,对于名称和姓氏字符串,我得到: 布兰妮……………………约翰逊…… ...................................... (点代表每个字符串末尾的空格字符)
这是我的代码:
void table_names (void)
{
ADDRESS *tmp_ptr;
printf ("All names in address book:\n");
tmp_ptr= hol;
printf(" ______________________________\n");
printf("| FIRST NAMES | LAST NAMES |\n");
printf("|________________|_____________|\n");
while(tmp_ptr!=NULL)
{
printf ("%s%s",tmp_ptr->name,tmp_ptr->lname);
tmp_ptr= tmp_ptr->next;
}
}
有关如何消除空格的任何帮助吗?
I have a struct list of names, last names, addresses... All inputted in separate CHAR strings.
The problem is whenever I paste one of these strings I also get a whole lot of whitespace afterwards.
For example, for Name and Last name strings, I get:
Britney............................................Johnson...................................
(dots represent space characters at the end of each string)
Here is my code:
void table_names (void)
{
ADDRESS *tmp_ptr;
printf ("All names in address book:\n");
tmp_ptr= hol;
printf(" ______________________________\n");
printf("| FIRST NAMES | LAST NAMES |\n");
printf("|________________|_____________|\n");
while(tmp_ptr!=NULL)
{
printf ("%s%s",tmp_ptr->name,tmp_ptr->lname);
tmp_ptr= tmp_ptr->next;
}
}
Any help on how to get rid of the whitespace?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为粘贴是指显示。
有了这个假设,我还假设每当 tmp_ptr->name 和 tmp_ptr->lname 形成时,它们的整个缓冲区都充满空格,并且只有在末尾才有 NUL 终止符(
'\0')。
无论在何处创建它们,您都需要通过在所有空白处放置
'\0'
来消除所有多余的空白。也许一个聪明的方法是向后工作以允许名称中存在空格。这也可以使用原始指针来完成,并且假设这是通过类似于以下内容的函数传入的:
I assume by paste that you mean display.
With that assumption, I also assume that whenever tmp_ptr->name and tmp_ptr->lname are formed, their entire buffer is filled with spaces and only at the end is there a NUL terminator (
'\0'
).Wherever those are created, you need to chop off all of the extra whitespace by putting a
'\0'
at the first sight of all blanks. Probably a smart approach would be to work backwards to allow for spaces in names.This could be done with the raw pointer as well, and it assumes that this is passed in through a function similar to:
要打印时不带尾随空格,请使用格式
.*s
和strcspn()
。.*s
采用int
值作为要打印的char
的最大数量。strcspn(s," ")
计算不包含' '
的初始前缀的长度。不需要修改
s
。如果姓氏中出现空格,则此方法不起作用。否则的话,工作量就有点大了。搜索最后一个
' '
(如果有)。To print without trailing spaces, use format
.*s
andstrcspn()
..*s
takes anint
value as the maximum number ofchar
to print.strcspn(s," ")
computes the length of the initial prefix not containing' '
.Modification of
s
is not needed. This method does not work should a space occur within the last name.Otherwise it is a bit more work. Search for the last
' '
, if any.