Delete a specific character from a string

Source: Internet
Author: User

Delete a specific character from a string
Question: enter two strings to remove all the characters from the first string. For example, if you enter "I am lavor_zl." and "I love you.", the first string after deletion becomes "amar_z ". The length of n time relative to the first string is required to be O (n ).

Solution: Use a bool array to store all the characters that appear in the second string. The array subscript represents the character. The length of this array is 256, because C/C ++ contains 256 characters in total. Traverse the first string and use a pointer or array subscript access to indicate a character in the first string currently accessed. Use another pointer or array subscript local to indicate the position where the current access character should be moved. When a character is accessed, it does not appear in the second string. The character is moved to the position indicated by local, and the position of the vacancy is moved back. Continue to access the next character. After traversing the first string, make the local character '\ 0 '.


Algorithm Implementation:

Void deleteCharsInOtherStr (char str [], char otherStr []) {if (str = NULL | str [0] = '\ 0' | otherStr = NULL | otherStr [0] =' \ 0') return; // if either of the two strings is null or empty, return bool isAppear [256]; for (int I = 0; I <256; I ++) {isAppear [I] = false;} int n = 0; while (otherStr [n]! = '\ 0') {isAppear [otherStr [n] = true; // otherStr [n] returns n ++ In the second string;} int local = 0; int access = 0; while (str [access]! = '\ 0') {if (! IsAppear [str [access]) // when the current access character does not appear in the second string {str [local] = str [access]; local ++ ;} access ++;} str [local] = '\ 0'; // After traversing the first string, set the local character to' \ 0 '}


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.