C:来自两个字符串的相同字符

时间:2016-08-11 18:07:27

标签: c algorithm

我有两个字符串:

while (Global.tmrStarted)
{
    Break();
    Thread.Sleep(500); 
    if (m_port == null || m_port.IsOpen == false) return;
    m_port.Write(new byte[] { 0 }, 0, 1);
    SendData();


    Break1();
    if (m_port1 == null || m_port1.IsOpen == false) return;
    m_port1.Write(new byte[] { 0 }, 0, 1);
    SendData1();
    Break2();

    if (m_port4 == null || m_port4.IsOpen == false) return;
    m_port4.Write(new byte[] { 0 }, 0, 1);
    SendData2();

    Thread.Sleep(100);
}

我正在尝试编写一个函数,该函数返回一个新字符串,该字符串具有来自两个字符串的相同字符而没有重复项(也是''重复)。例如:

char *str1 = "this is a test";
char *str2 = "ts bd a";

我该怎么做?

我尝试了什么:

char *retStr = GetSameChars(str1, str2); //returns "ts a";

当我尝试行char *GetSameChars(char str1[], char str2[]) { int found = -1, i , j = 0, biggest, index = 0; char *retArr, *star = '*'; int str1Len, str2Len, count = 0; str1Len = strlen(str1); str2Len = strlen(str2); biggest = str1Len > str2Len ? str1Len : str2Len; retArr = (char *)malloc(sizeof(char) * count); for (i = 0; i < str1Len; i++) { for (j = 0; j < str2Len; j++) { if (str1[i] == str2[j] && found == -1) { count++; found = j; } else if (str2[j] == str2[found]) str2[j] = star; //Throw an exception } found = -1; } retArr = (char *)malloc(sizeof(char) * count); j = 0; for (i = 0; i < str2Len; i++) if (str2[i] != '*') retArr[j++] = str2[i]; for (i = 0; i < str2Len; i++) printf("%c", retArr[i]); } 时,我遇到了异常。

我的错误是什么?

2 个答案:

答案 0 :(得分:2)

我的建议是:保持简单;了解C标准库;少写,多测试。

您的代码存在一些特定问题:您将错误的变量传递给malloc();你估计答案是适合两个字符串中较大字符串的大小,但它实际上适合两个中较小的字符串;修改参数字符串str2[j] = star - 您应该将参数视为只读;你不必要地malloc() retArr两次,当你分配第二个时泄漏第一个;你的算法根本不起作用。

虽然其他人建议的查找表会更有效,但让我们使用标准库例程strchr()来解决这个问题:

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

char *getSameChars(const char *string1, const char *string2) {

    size_t string1_length = strlen(string1);
    size_t string2_length = strlen(string2);
    size_t shortest = string1_length < string2_length ? string1_length : string2_length;

    char *common_pointer, *common = malloc(shortest + 1);

    *(common_pointer = common) = '\0';

    for (size_t i = 0; i < string1_length; i++) {
        // character found in both input strings, but not yet in common string
        if (strchr(string2, string1[i]) != NULL && strchr(common, string1[i]) == NULL) {
            *common_pointer++ = string1[i];
            *common_pointer = '\0';
        }
    }

    return common;
}

int main() {
    char *stringA = "this is a test";
    char *stringB = "ts bd a";

    char *result = getSameChars(stringA, stringB);

    printf("%s\n", result);

    free(result);

    return(0);
}

答案 1 :(得分:0)

您的代码抱怨是因为您正在尝试为char指定一个指针,以获取指针内的值,您需要使用*运算符,如下所示:

*star;

检查字母是否已经出现的好方法(如果要在所有ascii表上使用它然后是128)是使用查找表。首先,你需要声明一个数组字母表中所有字母的长度,如下所示:

char lut[26];

如果它是一个全局变量然后它将被设置为0,那么你需要做的就是转到你得到的char的索引并将其标记为1,如果稍后将能够确定是否为信已经上诉了。 例如:

lut[toupper(somechar) - 'A'] = 1;

在此示例中,您将查找表中的char设置为等于somechar变量1,标记它已经出现。

希望这会有所帮助。