在 C 中我如何 strcmp 只是开始的 2 个字符?然后与另一个字符串连接?像这样的东西:
char s[10];
scanf("%s",s);
/* if i input "cs332" or "cs234", anything start with cs */
if (strcmp("cs",???)==0)
strcat(s,"by professor");
在 C 中我如何 strcmp 只是开始的 2 个字符?然后与另一个字符串连接?像这样的东西:
char s[10];
scanf("%s",s);
/* if i input "cs332" or "cs234", anything start with cs */
if (strcmp("cs",???)==0)
strcat(s,"by professor");
您正在寻找strncmp
功能相同strcmp
但限制检查的字符数的功能。因此,您将使用它的长度为 2,比较字符串为"cs"
. 但是,这里还有一些其他问题。
首先,你的缓冲区不够大。当您将文本“by Professor”附加到它时,没有适合十个字符的缓冲区的字符串。
其次,健壮的代码永远不会与无界字符串格式说明符一起使用scanf
:这会导致缓冲区溢出问题。该scanf
系列适用于格式化输入,没有比用户输入更多的未格式化:-)
如果您想要一个强大的输入解决方案,请参阅我以前的答案之一。
第三,你应该总是假设连接一个字符串可能会溢出你的缓冲区,并引入代码来防止这种情况。你需要加起来:
并确保缓冲区足够大。
我将使用的方法是拥有一个(例如)200 字节的缓冲区,getLine()
从链接的答案(在下面复制以使该答案自包含)中使用足够小的大小(比如 100),那么你可以放心附加“教授”不会溢出缓冲区。
功能:
#include <stdio.h>
#include <string.h>
#define OK 0
#define NO_INPUT 1
#define TOO_LONG 2
static int getLine (char *prmpt, char *buff, size_t sz) {
int ch, extra;
// Get line with buffer overrun protection.
if (prmpt != NULL) {
printf ("%s", prmpt);
fflush (stdout);
}
if (fgets (buff, sz, stdin) == NULL)
return NO_INPUT;
// If it was too long, there'll be no newline. In that case, we flush
// to end of line so that excess doesn't affect the next call.
if (buff[strlen(buff)-1] != '\n') {
extra = 0;
while (((ch = getchar()) != '\n') && (ch != EOF))
extra = 1;
return (extra == 1) ? TOO_LONG : OK;
}
// Otherwise remove newline and give string back to caller.
buff[strlen(buff)-1] = '\0';
return OK;
}
测试代码:
// Test program for getLine().
int main (void) {
int rc;
char buff[10];
rc = getLine ("Enter string> ", buff, sizeof(buff));
if (rc == NO_INPUT) {
// Extra NL since my system doesn't output that on EOF.
printf ("\nNo input\n");
return 1;
}
if (rc == TOO_LONG) {
printf ("Input too long [%s]\n", buff);
return 1;
}
printf ("OK [%s]\n", buff);
return 0;
}
为什么不直接比较字符而不是调用 strcmp?
例如
if(s[0]=='c' && s[1]=='s'){ ... }
if (strncmp("cs",???, 2)==0) strcat(s,"by professor");
利用strncmp
有几种方法可以做到这一点。
字符串比较:
if ( s[0] == 'c' && s[1] == 's' )
是天真的方式,因为您不能轻松地将其扩展为稍长的代码(例如长度为 3/4 个字符)。
我猜你已经收集到你应该使用strncmp()
的权利?
字符串连接
不要使用 strcat。真的。如果你连接两个长度大于s
(目标)大小的字符串,你就有麻烦了。考虑snprint()
改用,如下所示:
char str[80];
snprintf(str, 80, "%s by professor", s);
或者,您可以使用strncat()
Heath 指出的:
char s[80];
strncat(s, " by professor", 80);
您可以使用strncmp。
编辑:
strcat(s,"by professor");
// s is an array of 10 characters. You need to make sure s is big enough
// to hold the string that needs to be concatenated + to have a terminating
// character '\0'.
是的,如前所述, strcmp 是首选方法。这只是一种不同的方式来做同样的事情。
#define CS 29539
char s[80];
scanf("%60s", s);
if( *(short *)s == CS )
if( strlcat(s, " by professor", sizeof(s)) >= sizeof(s) )
fprintf(stderr, "WARNING: truncation detected: %s", s);