Files
freeCodeCamp/curriculum/challenges/japanese/22-rosetta-code/rosetta-code-challenges/tokenize-a-string-with-escaping.md
2024-01-24 19:52:36 +01:00

3.3 KiB

id, title, challengeType, forumTopicId, dashedName
id title challengeType forumTopicId dashedName
594faaab4e2a8626833e9c3d エスケープ文字のある文字列をトークン化する 1 302338 tokenize-a-string-with-escaping

--description--

Write a function or program that can split a string at each non-escaped occurrence of a separator character.

次の 3 つの入力パラメータを受け取る必要があります:

  • The string
  • The separator character
  • The escape character

文字列のリストを出力する必要があります。

分割ルール:

  • The fields that were separated by the separators, become the elements of the output list.
  • 空のフィールドは、開始時と終了時にも保存する必要があります。

エスケープルール:

  • "Escaped" means preceded by an occurrence of the escape character that is not already escaped itself.
  • エスケープ文字が特別な意味を持たない文字の前に置かれた場合でも、エスケープとしてカウントされます (ただし、特別なことはしません)。
  • エスケープ処理のために使用されたエスケープ文字は、出力の一部にならないようにします。

関数が以下のテストケースを満たしていることを示してください。

以下の文字列が与えられました。

one^|uno||three^^^^|four^^^|^cuatro|

ここで、| を区切り文字として ^ をエスケープ文字として使用します。関数は次の配列を出力しなければなりません。

  ['one|uno', '', 'three^^', 'four^|cuatro', '']

--hints--

tokenize は関数とします。

assert(typeof tokenize === 'function');

tokenize は配列を返す必要があります。

assert(typeof tokenize('a', 'b', 'c') === 'object');

tokenize('one^|uno||three^^^^|four^^^|^cuatro|', '|', '^')['one|uno', '', 'three^^', 'four^|cuatro', ''] を返す必要があります。

assert.deepEqual(tokenize(testStr1, '|', '^'), res1);

tokenize('a@&bcd&ef&&@@hi', '&', '@')['a&bcd', 'ef', '', '@hi'] を返す必要があります。

assert.deepEqual(tokenize(testStr2, '&', '@'), res2);

--seed--

--after-user-code--

const testStr1 = 'one^|uno||three^^^^|four^^^|^cuatro|';
const res1 = ['one|uno', '', 'three^^', 'four^|cuatro', ''];

// TODO add more tests
const testStr2 = 'a@&bcd&ef&&@@hi';
const res2 = ['a&bcd', 'ef', '', '@hi'];

--seed-contents--

function tokenize(str, sep, esc) {
  return true;
}

--solutions--

// tokenize :: String -> Character -> Character -> [String]
function tokenize(str, charDelim, charEsc) {
  const dctParse = str.split('')
    .reduce((a, x) => {
      const blnEsc = a.esc;
      const blnBreak = !blnEsc && x === charDelim;
      const blnEscChar = !blnEsc && x === charEsc;

      return {
        esc: blnEscChar,
        token: blnBreak ? '' : (
          a.token + (blnEscChar ? '' : x)
        ),
        list: a.list.concat(blnBreak ? a.token : [])
      };
    }, {
      esc: false,
      token: '',
      list: []
    });

  return dctParse.list.concat(
    dctParse.token
  );
}