#1
by girafeeee » 5年前
「C言語によるはじめてのアルゴリズム入門」という本の3-6にある「文字列の照合」
でのソースコードで理解できないところがあります。
下記のコードで
for (p = text; p <= text + m - n; p++)
という部分があるのですがtextは文字列なのにfor分のなかにあり、整数であるm-nを加えていて、
このコードがどういう動きをしているのか分かりません。
p=text(文字列)とはどういう意味なのでしょうか
初歩的な質問で申し訳ないのですがお願いしますm(__)m
#include "stdafx.h"
#include <string.h>
char *search(char *, char *);
void main(void)
{
static char text[] = "This is a pen.That is a pensil.";
char *p, *key = "pen";
p = search(text, key);
while (p != NULL) {
printf("%s\n", p);
p = search(p + strlen(key), key);
}
}
char *search(char *text, char *key)
{
int m, n;
char *p;
m = strlen(text);
n = strlen(key);
for (p = text; p <= text + m - n; p++) {
if (strncmp(p, key, n) == 0)
return p;
}
return NULL;
}
「C言語によるはじめてのアルゴリズム入門」という本の3-6にある「文字列の照合」
でのソースコードで理解できないところがあります。
下記のコードで
for (p = text; p <= text + m - n; p++)
という部分があるのですがtextは文字列なのにfor分のなかにあり、整数であるm-nを加えていて、
このコードがどういう動きをしているのか分かりません。
p=text(文字列)とはどういう意味なのでしょうか
初歩的な質問で申し訳ないのですがお願いしますm(__)m
#include "stdafx.h"
#include <string.h>
char *search(char *, char *);
void main(void)
{
static char text[] = "This is a pen.That is a pensil.";
char *p, *key = "pen";
p = search(text, key);
while (p != NULL) {
printf("%s\n", p);
p = search(p + strlen(key), key);
}
}
char *search(char *text, char *key)
{
int m, n;
char *p;
m = strlen(text);
n = strlen(key);
for (p = text; p <= text + m - n; p++) {
if (strncmp(p, key, n) == 0)
return p;
}
return NULL;
}