Reputation: 3870
InputString: "I am unwell" "We need to go to the doctor" "How long will it take?"
.
OutputString: I am unwell We need to go to the doctor How long will it take?
The string needs to cleaned of all occurrences of the char "
. I can think of the following approacg
"
Repeat steps 1 and 2 , until strchr() returns a NULL pointer.
I feel this is very inefficient way to approach this problem. I need to know , if there are other methods to achieve this? Pseudo code or actual code will both be appreciated.
Upvotes: 9
Views: 10018
Reputation: 17903
You can accomplish this by visiting each char of the string once. You basically copy the string over itself, skipping the " characters:
pseudocode:
code:
// assume input is a char* with "I am unwell\" \"We need to go..."
char *src, *dest;
src = dest = input; // both pointers point to the first char of input
while(*src != '\0') // exit loop when null terminator reached
{
if (*src != '\"') // if source is not a " char
{
*dest = *src; // copy the char at source to destination
dest++; // increment destination pointer
}
src++; // increment source pointer
}
*dest = '\0'; // terminate string with null terminator
// input now contains "I am unwell We need to go..."
update: fixed some bugs in code
Upvotes: 9
Reputation: 21
If your string is not very big, the obvious answer would be to have a separate string. A single loop till you get \0 (End of string) Have a loop (Gives you O(n)) and a comparison to check if the current location of the string is the character in question (again O(n) )
In all :
s1 = original array
s2 = new array to store the final result
c = character in question.
current_pointer = 0
new_pointer =0
while(s1[current_pointer] != '\0') {
ele = s1[current_pointer] ;
if( ele != c) {
s2[new_pointer++] = ele
}
current_pointer++
}
Note that this method works only when string sizes are small. We need to go for better methods as size of string increases.
Hope this helps.
Upvotes: 0
Reputation: 57764
Instead of moving the characters "in-place" to overwrite the character being deleted, create a new string.
This minimizes the number of characters copied by copying each valid character once. With the original method, characters near the end of the string are copyied n times, where n is the number of invalid characters preceding it.
Upvotes: 0