'Add character at given position using pointers in C
Running into an issue with setting character at a specific position using pointers in C.
The code is accurately placing the character in the correct position, but the current character in that position is not being moved over.
The issue is that the current letter is being skipped over when position is found, but adding *dest++ = *string within the IF block when position is found causes the program to halt.
Example: the string is "bigmoney". Letter to add is 'X'. The position is 3.
Output should be "bigXmoney"
Current output is "bigXoney" using the code below.
Any suggestions would be appreciated. Thanks!
Updated code:
void addLetter(char string[STRING_LENGTH], char letterToAdd, int pos)
{
// store array in pointer
char *stringHolder = string;
char *dest = string;
int posCounter = 0;
// loop through string while not null
while (*stringHolder) {
// position found, add the character
if (posCounter == pos) {
*dest++ = letterToAdd;
} else {
*dest++ = *stringHolder;
}
// increment position counter
posCounter++;
// move the pointer position
stringHolder++;
}
//reset stringholder pointer;
*dest = '\0';
}
Solution 1:[1]
The easy way: Use std::string::insert.
Assuming std::string is forbidden in this assignment, start at the end of the string and work backward until you pass pos moving each character (including the null terminator) up one slot. Now you have an empty spot at pos and can safely write in the new value.
Solution 2:[2]
shorter if memcpy is allowed.
char * addLetter(char s[], char c, size_t pos)
{
int len = strlen(s);
if (pos > len || len + 1 >= STRING_LENGTH)
return NULL;
else
{
**memcpy(s + pos + 1, s + pos, len - pos);
s[pos] = c;**
return s;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user4581301 |
| Solution 2 | Shyamal Desai |
