我正在检查2个字符串是否是排列组合。我排序字符串然后比较每个字符彼此。但是,我认为我的排序过程也改变了原始字符串(我用指针和传递引用非常糟糕)。检查排列而不修改原始字符串C
有没有办法检查而不修改原始字符串?
我也试过使用strcpy,但我不知道如何使用它。 我在检查()函数试图此:
char temp[128];
strcpy(temp, word);
下面是我的代码。我所说的areAnagram功能从另一个功能是这样的:
void check(char *word, struct Entry *en) {
if (areAnagram(en->word, word) == 1) {
//printf("EW:%s W:%s\n", en->word, word);
//For example, this should return something like
// EW:silent W:listen
//But I got
// EW:eilnst W:eilnst
}
}
的条目结构:
typedef struct Entry {
char *word;
int len;
struct Entry *next;
} Entry;
这里是字谜检查过程:
void quickSort(char *arr, int si, int ei);
int areAnagram(char *str1, char *str2)
{
// Get lenghts of both strings
int n1 = strlen(str1);
int n2 = strlen(str2);
// If lenght of both strings is not same, then they cannot be anagram
if (n1 != n2) {
return 0;
}
// Sort both strings
quickSort (str1, 0, n1 - 1);
quickSort (str2, 0, n2 - 1);
int i;
// Compare sorted strings
for (i = 0; i < n1; i++) {
if (str1[i] != str2[i]) {
return 0;
}
}
return 1;
}
void exchange(char *a, char *b)
{
char temp;
temp = *a;
*a = *b;
*b = temp;
}
int partition(char A[], int si, int ei)
{
char x = A[ei];
int i = (si - 1);
int j;
for (j = si; j <= ei - 1; j++) {
if(A[j] <= x) {
i++;
exchange(&A[i], &A[j]);
}
}
exchange (&A[i + 1], &A[ei]);
return (i + 1);
}
void quickSort(char A[], int si, int ei)
{
int pi; /* Partitioning index */
if(si < ei) {
pi = partition(A, si, ei);
quickSort(A, si, pi - 1);
quickSort(A, pi + 1, ei);
}
}
最简单的解决办法是复制串和“惹”的副本而不是原始... – John3136
我试图在检查()函数做这样的事情: 字符strTemp [128]; strcpy(strTemp,word); 但它给了我一个错误。我从来没有使用strcpy,所以我不知道如何使用它。 – SusN