2016-11-24 7 views
-2

Pまたはpを含むアイテムをどのように取得し、この配列に現れる一致の数を返しますか?配列内の文字列で必要な特定の文字を見つける方法

  { SKU: 275, "Royal Gala Apples" }, 
      { SKU: 386, "Honeydew Melon"  }, 
      { SKU: 240, "Blueberries"   }, 
      { SKU: 916, "Seedless Grapes"  }, 
      { SKU: 385, "Pomegranate"   }, 
      { SKU: 495, "Banana"    }, 
      { SKU: 316, "Kiwifruit"   }, 
      { SKU: 355, "Chicken Alfredo"  }, 
      { SKU: 846, "Veal Parmigiana"  }, 
      { SKU: 359, "Beefsteak Pie"  }, 
      { SKU: 127, "Curry Chicken"  }, 
      { SKU: 238, "Tide Detergent"  }, 
      { SKU: 324, "Tide Liq. Pods"  }, 
      { SKU: 491, "Tide Powder Det." }, 
      { SKU: 538, "Lays Chips S&V"  }, 
      { SKU: 649, "Joe Org Chips"  }, 
      { SKU: 731, "Allen's Apple Juice" }, 
      { SKU: 984, "Coke 12 Pack"  }, 
      { SKU: 350, "Nestea 12 Pack"  }, 
      { SKU: 835, "7up 12 Pack"   } 
    }; 
+1

ルック()...あなたが始める必要があります...あなたはまだ問題がある場合は、あなたのコードを投稿し、あなたの特定の質問をします。 – TonyB

答えて

0

これは簡単な解決策になるかもしれません:

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

#define NPROD 6 
struct product { 
    int sku; 
    char *name; 
}; 

struct product products[NPROD] = { 
{ 275, "Royal Gala Apples" }, 
{ 386, "Honeydew Melon"  }, 
{ 240, "Blueberries"   }, 
{ 916, "Seedless Grapes"  }, 
{ 385, "Pomegranate"   }, 
{ 127, "Curry Chickens"  } 
}; 

int main() 
{ 
    int i, j, nfound; 
    nfound = 0; 
    for (i = 0; i < NPROD; i++) { 
     for (j = 0; j < (int)strlen(products[i].name); j++) { 
      if (products[i].name[j] == 'p' || 
       products[i].name[j] == 'P') { 
       /* Do whathever you want with this product */ 
       printf("%d %s\n", products[i].sku, 
         products[i].name); 
       nfound++; 
       break; 
      } 
     } 
    } 

    printf("found %d matching products\n", nfound); 
    return 0; 
} 

また、あなたは(strpbrkを使用する場合があります)TonyBは、ループのためのインナーを交換する提案として:

if (strpbrk("p", products[i].name) || 
    strpbrk("P", products[i].name)) { 
    /* Do whathever you want with this product */ 
    printf("%d %s\n", products[i].sku, products[i].name); 
    nfound++; 
} 

しかし、私はないですどのようにstrbpbrkが実装されているか確かめますが、単に文字列のサイズに対してforループを実行するだけで驚くことはありません。この場合、strbpbrkを2回呼び出すと、このソリューションは最初のソリューションよりも効率が悪くなります。おそらく良い解決策がありますが、私はあなたがそのアイデアを得ることを願っています。 これが出力されます:strpbrkのmanページで

275 Royal Gala Apples 
916 Seedless Grapes 
385 Pomegranate 
found 3 matching products 
関連する問題