使用指针算术的字符串的Anagram

时间:2016-10-17 23:36:06

标签: c pointers pointer-arithmetic

以下是查找字符串的anagram的代码。我正在使用指针数组来执行此操作,但希望使用指针算法来完成它。

matches:
matches: ()
matches: ()()()()()()
does not match: (
does not match: ((()()))
does not match: ))()))()()

- >如何使用指针算法找到它。

在while循环中:

#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] != '\0')
    {
       first[a[c]-'a']++;
       c++;
    }

    c = 0;

    while (b[c] != '\0')
    {
       second[b[c]-'a']++;
       c++;
    }

    for (c = 0; c < 26; c++)
    {
       if (first[c] != second[c])
          return 0;
    }

    return 1;
}

- &GT;我们可以将它修改为以下方式,以便它可以工作

while (a[c] != '\0')
{
   first[a[c]-'a']++;
   c++;
}

2 个答案:

答案 0 :(得分:0)

[ { "entity":{ "type":"postcode", "id":"P11516", "label":"18314 Divitz-Spoldershagen", "value":"18314" }, "matches":[ { "offset":0, "length":5 } ] }, { "entity":{ "type":"postcode", "id":"P11541", "label":"18314 Kenz-Küstrow", "value":"18314" }, "matches":[ { "offset":0, "length":5 } ] }, { "entity":{ "type":"postcode", "id":"P11549", "label":"18314 Löbnitz", "value":"18314" }, "matches":[ { "offset":0, "length":5 } ] }, { "entity":{ "type":"postcode", "id":"P11551", "label":"18314 Lüdershagen", "value":"18314" }, "matches":[ { "offset":0, "length":5 } ] } ] = public string callGACWithPLZSandbox(string plz) { var client = new RestClient("http://rest.sandbox-immobilienscout24.de"); var request = new RestRequest("restapi/api/gis/v2.0/geoautocomplete/DEU", Method.GET); client.ClearHandlers(); client.AddHandler("application/json", new JsonDeserializer()); request.AddQueryParameter("i", plz); request.AddQueryParameter("t", "postcode"); request.AddHeader("bla", "blub"); IRestResponse<Rootobject> response = client.Execute<Rootobject>(request); return response.Data.Property1[1].entity.label; } = class Rootobject { public Class1[] Property1 { get; set; } } class Class1 { public Entity entity { get; set; } public Match[] matches { get; set; } } class Entity { public string type { get; set; } public string id { get; set; } public string label { get; set; } public string value { get; set; } } class Match { public int offset { get; set; } public int length { get; set; } }

答案 1 :(得分:0)

使用指针处理数组的常用方法是初始化指向数组开头的指针,然后递增它,而不是每次都从头开始做指针算法索引。

char *c = a;
while (*c != 0) {
    first[*c - 'a']++;
    c++;
}

如果你需要对first使用指针算法,那么它将是:

    (*(first + *c - 'a'))++
相关问题