Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,959 questions

51,901 answers

573 users

How to check if each letter in a string maps to the first letter of a word in another string with Pascal

1 Answer

0 votes
program PatternMatch;

const
  MaxWords = 50;

type
  TStringArray = array[1..MaxWords] of string;

function ToLower(ch: char): char;
begin
  if (ch >= 'A') and (ch <= 'Z') then
    ToLower := chr(ord(ch) + 32)
  else
    ToLower := ch;
end;

function SplitWords(sentence: string; var words: TStringArray): integer;
var
  i, count, start: integer;
begin
  count := 0;
  start := 1;

  for i := 1 to length(sentence) + 1 do
  begin
    if (i > length(sentence)) or (sentence[i] = ' ') then
    begin
      if (i > start) then
      begin
        inc(count);
        words[count] := copy(sentence, start, i - start);
      end;
      start := i + 1;
    end;
  end;

  SplitWords := count;
end;

function MatchesPattern(pattern, sentence: string): boolean;
var
  words: TStringArray;
  wordCount, i: integer;
begin
  wordCount := SplitWords(sentence, words);

  if length(pattern) <> wordCount then
  begin
    MatchesPattern := false;
    exit;
  end;

  for i := 1 to wordCount do
  begin
    if ToLower(pattern[i]) <> ToLower(words[i][1]) then
    begin
      MatchesPattern := false;
      exit;
    end;
  end;

  MatchesPattern := true;
end;

var
  pattern, sentence: string;

begin
  pattern := 'jpcrg';
  sentence := 'java python c rust go';

  if MatchesPattern(pattern, sentence) then
    writeln('Pattern matches!')
  else
    writeln('Pattern does NOT match.');
end.



(*
run:

Pattern matches!

*)

 



answered Jan 6 by avibootz

Related questions

...