gpt4 book ai didi

c - 试图确保字符串缓冲区是一个合理的人名

转载 作者:行者123 更新时间:2023-11-30 19:22:08 25 4
gpt4 key购买 nike

这是我想知道为什么没有基本 C99 函数的任务之一某个名为 namesafe( char *in) 的地方就可以完成这项工作。这会很好在完美的世界中,对于用 UTF-8 希伯来语或 UTF-8 书写的名称完全没用也许是希腊语。然而,假设我被七位 ASCII 困住了,然后我尝试了以下:

  /* We may even go so far as to ensure that any apostrophe, or hyphen
* or period may only appear as single entities and not as two or three
* in a row. This does not, however, protect us from total non-sense
* such as D'Archy Mc'Clo.u. d.
*
* walk the first_name string and throw away everything that is
* not in the range A-Z or a-z, with the exception of space char which
* we keep. Also a single hyphen is allowed.
*
* This all seems smart but we are not protected from stupidity such
* As a name with spaces and dashes or hypens intermixed with letters
* or from the artist formally known as 'Prince'.
*/
char buffer[256];
j = 0;
for ( k=0; k<strlen(first_name); k++ ) {

/* Accept anything in the a - z letters */
if ( ( first_name[k] >= 'a' ) && ( first_name[k] <= 'z' ) )
buffer[j++] = first_name[k];

/* Accept anything in the A - Z letters */
if ( ( first_name[k] >= 'A' ) && ( first_name[k] <= 'Z' ) )
buffer[j++] = first_name[k];

/* reduce double dashes or hyphens to a single hyphen */
while (( first_name[k] == '-' ) && ( first_name[k+1] == '-' ))
k++;
if ( first_name[k] == '-' ) /* do I need this ? */
buffer[j++] = first_name[k];

/* reduce double spaces to a single space */
while (( first_name[k] == ' ' ) && ( first_name[k+1] == ' ' ))
k++;
if ( first_name[k] == ' ' ) /* do I also need this ? */
buffer[j++] = first_name[k];

}
/* we may still yet have terminating spaces or hyphens on buffer */
while ( ( j > 1 ) && (( buffer[j-1] == ' ' ) || ( buffer[j-1] == '-' )) )
j--;
buffer[j] = '\0';

/* Accept this new cleaner First Name */
strcpy ( first_name, buffer );

只要输入名称缓冲区不超过 255,似乎就可以很好地工作字符长度。然而,在第一次通过时,我想知道如何摆脱前导空格和诸如破折号和连字符以及可能的撇号的混合之类的噪音?

所以问题是......如何让它变得更好,而且我是否需要这些行我在哪里询问 (first_name[k] == '-') 是否与空格相同?我已经做了在缓冲区上行走寻找重复项并且应该落在连字符上或单个空格。正确的?

最佳答案

纯粹将其视为如何清理代码的抽象编程问题,您可以使用 isalpha() 来确保缓冲区仅包含字母表中的字母、单个连字符和单个空格:

for (k = 0; k < strlen(first_name); k++) {

if (isalpha (first_name[k])
buffer [j++] = first_name[k++];

else if (( first_name[k] == '-' ) && (isalpha (first_name [k+1])))
buffer [j++] = first_name[k++];

else if (( first_name[k] == ' ' ) && (isalpha (first_name [k+1])))
buffer [j++] = first_name[k++];

else
k++;
}

这只是一个草稿。我还没有实际尝试过,所以不能保证。此外,这也无法正确处理像“John - Paul”这样的名字在连字符前后都带有空格的情况;你最终会得到一个空格而不是一个连字符。如果您想捕获此类边缘情况,您可以添加几个额外的“else”子句。

也就是说,作为一个具体的现实解决方案,我同意最好将名称完全按照输入来处理。我自己有一个不寻常的名字,我厌倦了向人们解释是的,这确实是我的名字,不,你不能改变它以适应你对可接受的名字的想法。

关于c - 试图确保字符串缓冲区是一个合理的人名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18090965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com