返回学习页
知识点指南

Strings

String problems treat text as a sequence of characters or words. The code usually scans characters, counts matches, compares neighbours, or builds a new string.

什么时候使用

读题时可以留意这些信号。

  • The input contains words, letters, symbols, or encoded commands.
  • The task asks about patterns, repeated letters, initials, or transformations.
  • Character-by-character processing matches the story rule.

常见错误

提交前可以检查这些小陷阱。

  • Forgetting that strings are indexed like arrays.
  • Building a huge string when only a length or count is needed.
  • Ignoring exact case or exact symbol requirements.

怎么写成代码

把知识点翻译成变量、循环、判断和更新。

  • Read strings with normal string variables.
  • Access characters by index when position matters.
  • Use a loop over characters when every symbol is checked the same way.
  • Build output with append/+= only when the actual constructed string is required.

在 Block 题里长什么样

答题时通常会看到这些步骤被拆成代码块。

  1. 1Read the string or list of strings.
  2. 2Initialise count/result.
  3. 3Loop over characters or words.
  4. 4Check the target character/pattern.
  5. 5Update count or append to result.
  6. 6Print the final count/result.

题目里怎么出现

读题时先找这些信号,再决定答案区应该选哪些 blocks。

  • The statement says string, word, character, letter, binary, code, or initials.
  • The output is a count of symbols or a new string.
  • Exact matching matters, including uppercase/lowercase.

Count a target character

一个小型模板,展示代码和 blocks 的对应关系。

C++

int count = 0;
for (char c : S) {
    if (c == target) {
        count++;
    }
}
cout << count << '\n';

Python

count = 0
for c in S:
    if c == target:
        count += 1
print(count)

对应 block 顺序

  1. 1Read the string.
  2. 2Initialise count to 0.
  3. 3Loop through each character.
  4. 4Check whether the character is the target.
  5. 5Increase count.
  6. 6Output count.

建议先练这道题

可以先从 Subbookkeeper 开始,再回到这里复盘知识点信号。

打开题目