-1

In C, If I have a string assigned to a variable, and I want to change only the last 4 letters in that string for something else, how should I do it? strcat()? Something like:

int size;
char a[10] = "something";
size = strlen(a) - 4;

strcat(a + size, "1234");

Would that work? to get somet1234 ? or would it just be something1234 ?

Tas
  • 7,023
  • 3
  • 36
  • 51

3 Answers3

3

Use strncpy (to prevent an extra terminator from being appended) to overwrite from a given position:

strncpy(a + size, "1234", 4);

If you really want strcat, cut the string manually for strcat() to find the starting place to concatenate:

a[size] = '\0'; // Cut the string so strcat() know where to start
strcat(a, "1234");
iBug
  • 35,554
  • 7
  • 89
  • 134
  • Since `size` is computed relative to the trailing NUL, there is no danger is in overwriting it and `strcpy` would work fine. But I'd use `memcpy`. – rici Jan 28 '18 at 05:15
  • @rici `memcpy` is also a good option but it has nothing better than `strncpy`. I could have added `memcpy`, but that's only a copy of my existing code and a replacement of the function name. – iBug Jan 28 '18 at 05:18
0

No, that will not work. If you used strcpy() instead of strcat() it would.

Sid S
  • 6,037
  • 2
  • 18
  • 24
0
public string convertto(string abc,string replacewith,int len) 
                     //something,   1234 and     length to replace i-e 4
    {
        int g = strlen(abc);
        int f = g - len;
        j=0;
        char[] temp =new char[g];
        for (int i = 0; i < g; i++)
        {
            if (i >= f)
            {
                temp[i] = replaceWith[j];
                  j++;
            }
            else
            {
                temp[i] = abc[i];
            }
        }            
        return temp.ToString();
    } 

// It will return somet....

hassan mirza
  • 139
  • 2
  • 8