微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C-如何使用指针更轻松地指向字符串数组的开头

如何解决C-如何使用指针更轻松地指向字符串数组的开头

我有一个功能。此功能旨在在称为客户应收帐款数据库的结构数组中遍历客户名称。该代码使用指针来引用结构数组,以访问数据库中每个索引处的每个客户名称。该代码应该先清除所有非字母字符,然后再将每个名称的首字母用大写字母表示。

/**********************************************************************/
/*     Titlecases and removes all nonletter characters from names     */
/**********************************************************************/
void clean_names(struct customer *p_customer_start,int customer_number)
{
   struct customer *p_last_name; /* Points to every customer          */
   char *p_fast,/* Points to customer's name         */
        *p_slow;                 /* Points to all letters             */

   for(p_last_name = p_customer_start;
      (p_last_name - p_customer_start) < customer_number; p_last_name++)
   {
      p_fast = p_last_name->last_name;
      p_slow = p_last_name->last_name;

      while(*p_fast != END_OF_STRING)
      {
         if(isalpha(*p_fast))
            *p_slow++ = tolower(*p_fast);
         p_fast++;
      }
      *p_slow = END_OF_STRING;
      *(p_slow-strlen(p_last_name->last_name)) =
      toupper(*(p_slow-strlen(p_last_name->last_name)));
   }
   return;
}

我在排队时很难过

*(p_slow-strlen(p_last_name->last_name)) = toupper(*(p_slow-strlen(p_last_name->last_name)));

struct customer一个字符数组char last_name[21]。我在使用指针指向字符数组中的第一项并将其大写时遇到麻烦。我使用的方法是我发现唯一可行的解​​决方案。 p_slow指向字符串末尾的NULL字符。我使用指针算术使用strlen()解除对p_slow - total string length的引用,使其指向数组p_last_name->last_name中的第一项。

我不是在寻找一个布局清晰的解决方案,而是在寻找简化代码的建议。

解决方法

您不需要该复杂的表达式即可找到名称的第一个字符。 p_last_name->last_name包含更新后的名称,因此您可以引用它来访问第一个字符。

*p_last_name->last_name = toupper(*p_last_name->last_name);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。