Tag: 字符串

关于字符串长度,终止NUL等

我正在学习C,我对char数组和字符串之间的差异以及它们如何工作感到困惑。 问题1: 为什么源代码1和源代码2的结果有所不同? 源代码1: #include #include int main(void) { char c[2]=”Hi”; printf(“%d\n”, strlen(c)); //returns 3 (not 2!?) return 0; } 源代码2: #include #include int main(void) { char c[3]=”Hi”; printf(“%d\n”, strlen(c)); //returns 2 (not 3!?) return 0; } 问题2: 字符串变量与char数组有何不同? 如何使用允许\ 0存储的最小所需索引号来声明它们(请阅读下面的代码)? char name[index] = “Mick”; //should index be 4 or 5? char name[index] = {‘M’, […]

检查char *指针是否为以null结尾的字符串的便携方法

我有一个C函数,它接受一个char *指针。 函数的前提条件之一是指针参数是以空字符结尾的字符串 void foo(char *str) { int length = strlen(str); // … } 如果str不是指向以null结尾的字符串的指针,则strlen崩溃。 是否有一种可移植的方法来确保char *指针确实指向以null结尾的字符串? 我正在考虑使用VirtualQuery来查找不可读的str后的最低地址,如果我们在str的开头和该地址之间没有看到空终止符,则str不指向以null结尾的字符串。

使用数组上的字符串切换语句

#include int main(){ char name[20]; printf(“enter a name “); scanf(“%s”,name); switch(name[20]){ case “kevin” : printf(“hello”); break; } printf(“%s”,name); getch(); } 它似乎不起作用。 这可能吗? 我的意思是我们可以用任何方式创建一个字符串的switch语句。 实际上如何解决问题?

从字符串c ++中读取所有整数

我需要一些帮助,从std :: string中获取所有整数,并将每个整数转换为int变量。 字符串示例: hi 153 67 216 我希望程序忽略“blah”和“hi”并将每个整数存储到int变量中。 所以它就像是: a = 153 b = 67 c = 216 然后我可以自由地分别打印每个像: printf(“First int: %d”, a); printf(“Second int: %d”, b); printf(“Third int: %d”, c); 谢谢!

打印浮点数的整数部分

我试图弄清楚如何在不使用库函数的情况下打印浮点数。 打印浮点数的小数部分结果非常简单。 打印整体部件更难: static const int base = 2; static const char hex[] = “0123456789abcdef”; void print_integral_part(float value) { assert(value >= 0); char a[129]; // worst case is 128 digits for base 2 plus NUL char * p = a + 128; *p = 0; do { int digit = fmod(value, base); value /= base; […]

字符串连接在C中没有strcat

我在连接C中的字符串时遇到问题,没有strcat库函数。 这是我的代码 #include #include #include int main() { char *a1=(char*)malloc(100); strcpy(a1,”Vivek”); char *b1=(char*)malloc(100); strcpy(b1,”Ratnavel”); int i; int len=strlen(a1); for(i=0;i<strlen(b1);i++) { a1[i+len]=b1[i]; } a1[i+len]='\0'; printf("\n\n A: %s",a1); return 0; } 我对代码进行了更正。 这很有效。 我现在可以不用strcpy吗?

string + int在C中执行什么操作?

我无法弄清楚这个表达式: str + n 其中char str[STRING_LENGTH]和int n 。 我已经在Java中工作了很多,并且直到现在才假设它是字符串和整数的串联,我现在怀疑它。 这是什么意思?

char * a的strcat问题

包括 #include int main() { char *array[10]={}; char* token; token = “testing”; array[0] = “again”; strcat(array[0], token); } 为什么它会返回分段错误? 我有点困惑。

在宏中连接字符串 – C ++

连接宏中定义的字符串的最简单方法是什么。 即我正在寻找的伪代码将是: #define ROOT_PATH “/home/david/” #define INPUT_FILE_A ROOT_PATH+”data/inputA.bin” #define INPUT_FILE_B ROOT_PATH+”data/inputB.bin” … #define INPUT_FILE_Z ROOT_PATH+”data/inputZ.bin” 我知道的唯一方法是在代码中使用strcat,或者使用字符串类然后使用c_str方法,但是当我有大量输入文件时它会变得混乱。 我想直接使用INPUT_FILE_A等,而不是有很多局部变量。 有没有一个很好的方法来做到这一点? 谢谢。

strcat vs strncat – 什么时候应该使用哪个函数?

一些静态代码分析器工具建议为了安全起见,所有strcat用法都应该替换为strncat? 在程序中,如果我们清楚地知道目标缓冲区和源缓冲区的大小,是否仍然建议使用strncat? 另外,根据静态工具的建议,是否应该使用strcat?