1

我正在编写以下代码以找出给定字符串中存在所需的字符串,如果发现我想用所需的替换它们。我尝试如下,但是对于替换我还没有做有人可以帮助我

#include <stdio.h>
#include <string.h>
int main(void)
{
char *str;
   const char text[] = "Hello atm adsl";
   const char *arr[] = {"atm", "f/r", "pc","adsl"}; // If found I would like to replace them with Atm, F/R,PC,ADSL
int i=strlen(*arr);
for(int j=0;j<i;j++)
{
    str=arr[j];
   const char *found = strstr(text, arr[j]);
switch(str)
{
    case "Atm":
    break;
}

   puts(found ? "found it" : "didn't see nuthin'");
   return 0;

}
}

我收到以下错误

invalid conversion from const char* to char*switch quantity not an integer

有人能帮我吗

4

3 回答 3

1

C cannot do switch with string.

这可能会回答您的问题:在 C 中打开字符串的最佳方法

于 2012-06-23T10:23:18.967 回答
1

试试这个!!!

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

int main(void) {
    char *token;
    char text[] = "Hello atm adsl";
    char *arr[] = {"atm", "f/r", "pc","adsl"}; // If found I would like to replace them with Atm, F/R,PC,ADSL

    char textTmp[500] ="";

    token = strtok (text, " "); // catch single words
    while(token != NULL) {

        printf("%s\n", token);
        if (strncmp(token, arr[0], strlen(arr[0])) == 0) {
            token[0] = 'A';
        }else if (strncmp(token, arr[1], strlen(arr[1])) == 0) {
            token[0] = 'F';
            token[1] = '/';
            token[2] = 'R';
        } else if (strncmp(token, arr[2], strlen(arr[2]))== 0) {
            token[0] = 'P';
            token[1] = 'C';
        } else if (strncmp(token, arr[3], strlen(arr[3]))== 0) {
            token[0] = 'A';
            token[1] = 'D';
            token[2] = 'S';
            token[3] = 'L';
        }
        strncat(textTmp, token, strlen(token));
        strncat(textTmp, " ", 1);
        token = strtok (NULL, " ");
    }

    textTmp[strlen(textTmp)-1] = '\0';

    strncpy(text, textTmp, strlen(textTmp));
    printf("%s\n", text);


    return 0;



}
于 2012-06-23T11:03:55.123 回答
0
  1. 在 C 中,switch 只能用于整数情况——因此会出现错误。

  2. 您的分配str=arr[j]无效,因为您将 a 分配const char*给 a char *。C不会在赋值时按值复制...如果您想从其中复制值const char*然后对其进行更改,那么您需要malloc自己的记忆和strcpy那里。

于 2012-06-23T10:22:15.613 回答