简体   繁体   English

C中的字符串缩写字符序列

[英]string abbreviation characters sequence in C

我需要编写一个函数,它接受像“abcdef”这样的字符串并将其转换为“af”,或将“589”转换为“5-9”,我可以使用 stdio.h 和 string.h 中的哪些函数?

You need to find the start and end of runs.您需要找到运行的开始和结束。 It's easier if you consider every character to be part of a run, so you might runs of length 1 or more.如果您将每个角色都视为运行的一部分,则更容易,因此您的运行长度可能为 1 或更长。

When you find the end of a run, you need to do different things depending on the length of the run.当你找到跑步​​的终点时,你需要根据跑步的长度做不同的事情。

  • Length of run = 1: Print the only character of the run.运行长度 = 1:打印运行的唯一字符。
  • Length of run = 2: Print both characters of the run.运行长度 = 2:打印运行的两个字符。
  • Length of run = 3: Print the first and last characters of the run with a dash in between.运行长度 = 3:打印运行的第一个和最后一个字符,中间有一个破折号。

With that in mind, we could use the following algorithm:考虑到这一点,我们可以使用以下算法:

  1. Create a pointer pointing at the first character of the string.创建一个指向字符串第一个字符的指针。
  2. While the pointed character isn't NUL,虽然尖头字符不是 NUL,
    1. Print the pointed character.打印尖头字符。
    2. Set the length of the run to 0.将运行的长度设置为 0。
    3. Loop,环形,
      1. Save the pointed character.保存尖角字符。
      2. Increment the pointer.增加指针。
      3. Increment the length of the run.增加运行的长度。
      4. If the pointed character is NUL,如果指向的字符是 NUL,
        1. Break.休息。
      5. If the pointed character isn't one more than the saved character,如果指向的字符不比保存的字符多一个,
        1. Break.休息。
    4. If the length of the run is 2+,如果运行的长度是 2+,
      1. If the length of the run is 3+,如果运行的长度是 3+,
        1. Print a dash.打印一个破折号。
      2. Print the saved character.打印保存的字符。
  3. Print a line feed.打印换行符。

You should run through the above algorithm on paper, with "4abcz35xy" as input.您应该在纸上运行上述算法,输入"4abcz35xy" While you do, keep track of the current value of the variables (the pointer, the run length and the saved character).执行此操作时,请跟踪变量的当前值(指针、运行长度和保存的字符)。

         +---+---+---+---+---+---+---+---+---+---+---+
         |'4'|'a'|'b'|'c'|'z'|'3'|'4'|'5'|'x'|'y'| 0 |
         +---+---+---+---+---+---+---+---+---+---+---+
           ^
Pointer    |
+-------+  |
|     -----+
+-------+

Run length
+-------+
|       |
+-------+

Saved character
+-------+
|       |
+-------+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM