Interview question (2) -- convert string-number of characters inserted

Source: Internet
Author: User
Requirement: Convert the string-the number of characters inserted, such as the aaab character string. The number of characters inserted is changed to aaa3b1. The Code is as follows: /**//*********************************** *************************************
* Conversion string -- number of characters inserted
* For example, aaab is changed to aaa3b1.
**************************************** ********************************/

# Include <stdlib. h>
# Include <stdio. h>
# Include <string. h>

# Define maxcount 2*100 // The length of the input string cannot exceed 100

Char * Transformation (char * Str)
...{
Int Len = strlen (STR );
Char * Buf = new char [Len + 1]; // The number of characters that are stored after the character

Char * P = STR;
Char * q = p + 1;
Int COUNT = 1;
While (* q)
...{
If (* P = * q)
...{
Count ++;
P ++;
Q ++;
}
Else
...{
ITOA (count, Buf, 10 );
Int nbits = strlen (BUF );
Strcat (BUF, q );
* Q = 0;
Strcat (STR, Buf );
Q + = nbits;
P = Q;
Q = p + 1;
Count = 1;
}
}

// Number of the last identical characters
ITOA (count, Buf, 10 );
Strcat (STR, Buf );

Delete [] Buf;
Buf = NULL;
Return STR;
}

// Display menu
Void show_menu ()
...{
Printf ("---------------------------------------------");
Printf ("input command to test the program ");
Printf ("I or I: input string to test ");
Printf ("Q or Q: Quit ");
Printf ("---------------------------------------------");
Printf ("$ input command> ");
}

Void main ()
...{
Char sinput [10];
Char STR [maxcount];

Show_menu ();

Scanf ("% s", sinput );
While (stricmp (sinput, "Q ")! = 0)
...{
If (stricmp (sinput, "I") = 0)
...{
Printf ("Please input an string :");
Scanf ("% s", & Str );
Printf ("Before transformation: % s", STR );
Char * pstr = Transformation (STR );
Printf ("after transformation: % s", pstr );
}

// Enter the command
Printf ("$ input command> ");
Scanf ("% s", sinput );
}
}

 

The running result is as follows:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.