Radu Gabriel
Radu Gabriel

Reputation: 111

Add one character from a string to the end of another string (strcat)

for (unsigned int i = 0; i < strlen(s); i++) {
  if (s[i] != ' ') 
    strcat(p, s[i]);

I want to add the current character of the s string at the end of the p string provided it is not a space. How do I do that using strcat? The code above gives the following error "invalid conversion from 'char' to 'const char*'".

I want to use strcat because this way I don't have to store an index for p string in order to know where to place the current character. I hope this makes sense.

Also, I need to do this using array of chars, not c-strings or whatever those are called.

Upvotes: 2

Views: 1011

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 755026

A more sensible algorithm would avoid using strcat() or strncat() altogether:

int j = strlen(p);
for (int i = 0; s[i] != '\0'; i++)
{
    if (s[i] != ' ')
        p[j++] = s[i];
}
p[j] = '\0';

This avoids quadratic behaviour which using strlen() and strcat() (or strncat()) necessarily involves. It does mean you need to keep a track of where to place characters in p, but the work involved in doing that is trivial. Generally speaking, the quadratic behaviour won't be a problem on strings of 10 characters or so, but if the strings reach 1000 bytes or more, then quadratic behaviour becomes a problem (it takes 1,000,000 operations instead of 1,000 operations — that can become noticeable).

Upvotes: 4

kkica
kkica

Reputation: 4104

First, you need addresses (the array itself is an address to the first element) to pass to the strcat, not a char. That is why you need to use the & operator before s[i].

You have a working example here

#include <stdio.h>
#include <string.h>
int main()
{

    char s[50]= "Hello World";
    char p[50]= "Hello World";
    for(unsigned int i=0;i<strlen(s);i++){
    if(s[i]!=' ') 
    strncat(p,&s[i],1);
    }
    puts(p);
    return 0;
}

Upvotes: 0

Related Questions