C中的字符串操作:这可能吗?

时间:2014-04-25 12:11:55

标签: c string

我正在尝试在进行比较时在另一个字符串的末尾添加一个字符串。这就是我在java中做的事情(可能不是合法的java代码 - 已经有一段时间了):

String input = "addl $1,%eax";

String[] registers = {"eax", "abx", "ebx", "edx"};
String s = "addl $1,%";

for (int i = 0 ; i < 4; i++) {
    if (input.equals(s + registers[i])) {
        printf("Match");
        // write out optimized code with specified register
    }
}

我根本不确定如何在C中做到这一点。我已经尝试了以下但我的程序一直在崩溃(我认为是因为一些指针无意义):

 ...
 char *in = "Hell";
 char *pattern = "Hello";  
 const char *a[2];
 a[0] = "e";
 a[1] = "o";
 char *result = strcat(in,a[1]);
 if (strcmp(in, result) == 0) {

 printf("Helloooooooooooooooo");

 }

任何人都可以启发我请问如何在C中进行这种字符串操作?

5 个答案:

答案 0 :(得分:3)

您正尝试使用strcat修改字符串文字。这将调用未定义的行为。在C中,您无法修改字符串文字。声明

char *in = "Hell"; 

相当于

char const *in = "Hell";  

如果您想修改它,请将in声明为数组

char in[6] = "Hell";  

建议阅读:c-faq: Question 1.32

答案 1 :(得分:1)

您在strcat上调用in,这是指向不可变字符串文字(只读内存中的字符数组)的指针。根据定义,您不能将任何其他字符连接到该数组。

我已经更详细地解释了这种现象here

就像链接问题一样,您可以通过将char *in定义为字符数组来解决此问题:

char in[MAX_IN_LEN] = "Hell";

哪个将字符串文字中的字符复制到字符数组中。然后,如果数组足够大,您可以根据需要进行连接。

答案 2 :(得分:1)

你可以试试这个:

const char *input = "addl $1,%eax";  // For testing the code

char *registers[] = {"eax", "abx", "ebx", "edx"}; 
const char *s = "addl $1,%";
char temp[30];   // temp array to store possible commands in complete form

for (int i = 0 ; i < 4; i++) {
    strcpy(temp, s);  // Copy the common part to `temp`
    if (strcmp(input, strcat(temp, registers[i])) == 0) 
          // Compare the input string with possible command string
    {
        printf("Match");
        // write out optimized code with specified register
    }
}

您可以详细了解strcpystrcmpstrcat here

答案 3 :(得分:0)

以下两个陈述在C中有所不同。

char *in1 = "Hello";
char in2[6] = "Hello";

在第一个语句中,字符指针in1指向字符串文字Hello。在这里,您无法更改字符串文字。 但是在第二个语句中,您将字符串Hello存储在字符数组in2中。 这可以修改为in2[0] = 'h';

之类的其他内容

答案 4 :(得分:0)

问题是您正在尝试将字符串连接到常量字符串。无法修改常量字符串。

声明char* test = "My string"时,编译器自动生成变量const,因为字符串文字是代码中const char*的表示。

strcat想要一个char*,它包含一个以空字符结尾的字符串,并且有足够的空间来连接第二个参数。要正确解决这个问题,你必须将第一部分复制到缓冲区,然后将你的附录连接到该缓冲区,如下所示:

const char* source = "Hello ";
const char* appendix = "world!";

uint32_t bufLen = strlen(source) + strLen(appendix) + 1; // length of both + null-termination
char buf[bufLen];
strcpy(buf, source);
strcat(buf, appendix);
// now buf contains your concatenated string