问题描述
我是c的新手,我遇到字符串有问题,任何人都可以给我一些
快速指针或指向好的c字符串教程?以下是我正在制作的
计划。
亲切的问候,
Anthony Irwin
#include< stdio.h>
char teststring [40] =" test string now";
char teststring1 [40] ;
int main(){
printf(" teststring =%s",teststring);
strcpy(teststring1 ,teststring);
printf(" \\\
teststring1 =%s",teststring1);
/ *如何为teststring分配新值说
*值我改变了字符串文本 * /
printf(" \ n\\\
II将teststring更改为=%s \ n",teststring);
返回0;
}
Hi,
I am new to c and am having trouble with strings can anyone give me some
quick pointers or point me to a good c strings tutorial? Below is a
program I am working on.
Kind Regards,
Anthony Irwin
#include <stdio.h>
char teststring[40] = "test string now";
char teststring1[40];
int main() {
printf("teststring = %s", teststring);
strcpy(teststring1, teststring);
printf("\nteststring1 = %s", teststring1);
/* How can I assign a new value to teststring say
* the value "I changed string text" */
printf("\n\nI changed teststring to = %s\n", teststring);
return 0;
}
推荐答案
strncpy(teststring,我更改了字符串文本,sizeof teststring-1);
或
sprintf(teststring,"%。* s",sizeof teststring-1," I changed string
text");
转换说明符%。Ns表示不应写入不超过N
的字符;例如,我们可以写出
%。39s。使用*而不是常量意味着在
中指定了printf()的一个参数(在本例中,通过表达式
sizeof teststring-1)。
表达式sizeof teststring-1给出了目的地的大小
缓冲区,少了0个终结符的一个字符,因此在这两种情况下,没有
将超过39个字符写入teststring。 />
strncpy(teststring, "I changed string text", sizeof teststring-1);
or
sprintf(teststring, "%.*s", sizeof teststring-1, "I changed string
text");
The conversion specifier "%.Ns" indicates that no more than N
characters should be written; for example, we could have written
"%.39s". Using * instead of a constant means that N is specified in
one of the arguments to printf() (in this case, by the expression
sizeof teststring-1).
The expression "sizeof teststring-1" gives the size of the destination
buffer, less one character for a 0 terminator, so in both cases, no
more than 39 characters are being written to teststring.
这篇关于C和字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!