简体   繁体   中英

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.

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.
  • Length of run = 2: Print both characters of the run.
  • Length of run = 3: Print the first and last characters of the run with a dash in between.

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,
    1. Print the pointed character.
    2. Set the length of the run to 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,
        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+,
      1. If the length of the run is 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. 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
+-------+
|       |
+-------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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