0

我有两个字符串,一个带有电子邮件地址,另一个是空的。如果电子邮件地址是 eg "abc123@gmail.com",我需要传递电子邮件地址的开头,就在@第二个字符串之前。例如:

第一个字符串:"abc123@gmail.com"

第二个字符串:"abc123"

我写了一个循环,但它不起作用:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char email[256] = "abc123@gmail.com";
char temp[256];
int i = 0;

while (email[i] != '@')
{
      temp = strcat(temp, email[i]);
      i++;
}

printf ("%s\n", temp);
system ("PAUSE");
return 0;
}

基本上,我每次都从电子邮件地址中提取一个字符,并将其添加到新字符串中。例如,如果新字符串上有一个,现在我b也将使用strcat....

4

4 回答 4

2
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
char email[256] = "abc123@gmail.com";
char temp[256];
size_t i = 0;

#if 0
for (i=0; email[i] && email[i] != '@'; i++) {;}

   /* at the end of the loop email[i] is either the first '@',
   ** or that of the terminating '\0' (aka as strlen() )
   */

#else

i = strcspn(email, "@" );

   /* the return value for strcspn() is either the index of the first '@'
   * or of the terminating '\0'
   */

#endif

memcpy (temp, email, i);
temp[i] = 0;


printf ("%s\n", temp);
system ("PAUSE");
return 0;
}

更新:一种完全不同的方法是在循环内进行复制(我想这是 OP 的意图):

for (i=0; temp[i] = (email[i] == '@' ? '\0' : email[i]) ; i++) {;}
于 2012-06-09T12:31:28.683 回答
2

有更好的方法来解决这个问题(例如通过找到@(通过strcspn或其他方式)的索引并执行 a memcpy),但是您的方法非常接近工作,因此我们可以进行一些小的调整。


正如其他人所指出的,问题出在这一行:

temp = strcat(temp, email[i]);

据推测,您正试图将ith 位置的字符复制email到 的相应位置temp。但是,strcat这样做不是正确的方法:将strcat数据从一个复制char*到另一个char*,也就是说,它复制字符串。你只想复制一个字符,这正是=它所做的。

从更高的层次来看(所以我不只是告诉你答案),你想将适当的字符设置为适当temp的字符email(你需要使用i索引emailtemp)。

另外,请记住 C 中的字符串必须以 终止'\0',因此您必须在复制完字符串后将下一个字符设置为tempto 。'\0'(按照这种思路,您应该考虑如果您的电子邮件字符串中没有一个会发生@什么,您的while循环将继续超过字符串的末尾email:请记住,您可以判断您是否在字符串的末尾通过character == '\0'或仅用character作条件。)

于 2012-06-09T12:54:50.253 回答
2

指针。首先, strcat() 返回一个 char 指针,由于某种原因,C 不能将其转换为 char 数组(我听说所有 C 程序员都必须知道)。其次,strcat() 的第二个参数应该是一个 char 指针,而不是一个 char。

替换应该可以解决问题temp = strcat(temp, email[i]);temp[i] = email[i];

此外,循环结束后,以空字符终止字符串。

temp[i] = '\0';

(循环结束后,i等于提取字符串的长度,temp[i]终端应该去的地方也是如此。)

于 2012-06-09T12:57:08.060 回答
0

您可能想尝试使用strtok()

于 2012-06-09T12:30:46.543 回答