使用指针算术的字符串的字谜
Anagram of a string using pointer arithmatic
这是查找字符串的变位词的代码。我正在使用指针数组来执行此操作,但想使用指针算法来执行此操作。
#include <stdio.h>
int check_anagram(char [], char []);
int main()
{
char a[100], b[100];
int flag;
printf("Enter first string\n");
gets(a);
printf("Enter second string\n");
gets(b);
flag = check_anagram(a, b);
if (flag == 1)
printf("\"%s\" and \"%s\" are anagrams.\n", a, b);
else
printf("\"%s\" and \"%s\" are not anagrams.\n", a, b);
return 0;
}
int check_anagram(char a[], char b[])
{
int first[26] = {0}, second[26] = {0}, c = 0;
while (a[c] != '[=10=]')
{
first[a[c]-'a']++;
c++;
}
c = 0;
while (b[c] != '[=10=]')
{
second[b[c]-'a']++;
c++;
}
for (c = 0; c < 26; c++)
{
if (first[c] != second[c])
return 0;
}
return 1;
}
--> 如何使用指针运算并找到它。
在 while 循环中:
while (a[c] != '[=11=]')
{
first[a[c]-'a']++;
c++;
}
--> 我们可以将其修改为以下方式以便它可以工作吗
while(*(a+c)!='[=12=]')
{
*(first *(a+c)-'a')++;
c++;
}
first[a[c]-'a']++
= first[*(a+c)-'a']++
= (*(first+(*(a+c)-'a')))++
通常使用指针处理数组的方法是初始化一个指向数组开头的指针,然后递增它,而不是每次都从头开始对索引进行指针运算。
char *c = a;
while (*c != 0) {
first[*c - 'a']++;
c++;
}
如果您还需要对 first
使用指针算法,那么它将是:
(*(first + *c - 'a'))++
这是查找字符串的变位词的代码。我正在使用指针数组来执行此操作,但想使用指针算法来执行此操作。
#include <stdio.h>
int check_anagram(char [], char []);
int main()
{
char a[100], b[100];
int flag;
printf("Enter first string\n");
gets(a);
printf("Enter second string\n");
gets(b);
flag = check_anagram(a, b);
if (flag == 1)
printf("\"%s\" and \"%s\" are anagrams.\n", a, b);
else
printf("\"%s\" and \"%s\" are not anagrams.\n", a, b);
return 0;
}
int check_anagram(char a[], char b[])
{
int first[26] = {0}, second[26] = {0}, c = 0;
while (a[c] != '[=10=]')
{
first[a[c]-'a']++;
c++;
}
c = 0;
while (b[c] != '[=10=]')
{
second[b[c]-'a']++;
c++;
}
for (c = 0; c < 26; c++)
{
if (first[c] != second[c])
return 0;
}
return 1;
}
--> 如何使用指针运算并找到它。
在 while 循环中:
while (a[c] != '[=11=]')
{
first[a[c]-'a']++;
c++;
}
--> 我们可以将其修改为以下方式以便它可以工作吗
while(*(a+c)!='[=12=]')
{
*(first *(a+c)-'a')++;
c++;
}
first[a[c]-'a']++
= first[*(a+c)-'a']++
= (*(first+(*(a+c)-'a')))++
通常使用指针处理数组的方法是初始化一个指向数组开头的指针,然后递增它,而不是每次都从头开始对索引进行指针运算。
char *c = a;
while (*c != 0) {
first[*c - 'a']++;
c++;
}
如果您还需要对 first
使用指针算法,那么它将是:
(*(first + *c - 'a'))++