ft_strjoin

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.6 kB
5
Indexable
Never
#include <stdio.h>
#include <stdlib.h>

int	ft_strlen(char *str)
{
	int		i;
	
	i = 0;
	while (str[i] != '\0')
		i++;
	return (i);
}

int	ft_total_len(char **str, int size)
{
	int		i;
	int		total;

	i = 0;
	total = 0;
	while (i < size)
	{
		total = total + ft_strlen(str[i]);
	}
	return (total);
}

char	*ft_redamagic(char *s1, char *s2, char *s3)
{
	int		i;
	int		j;
	int		k;

	i = 0;
	j = 0;
	k = 0;
	while (s1[i] != '\0')
		i++;
	while (s3[j] != '\0')
	{
		s1[i+j] = s3[j];
		j++;
	}
	while (s2[k] != '\0')
	{
		s1[i+j+k] = s2[k];
		k++;
	}
	s1[i+j+k] = '\0';
	return (s1);
}

char	*ft_idobigjobs(char *dest,char **strings, char *sep,int size)
{
	int		i;
	int		j;
	int		k;

	i = 0;
	j = 0;
	k = 0;
	while (i < size)
	{
		dest = ft_redamagic(dest, strings[i], sep);
		i++;
		if (i < size)
		{
			while(dest[j] != '\0')
				j++;
			while (sep[k] != '\0')
			{
				dest[j+k] = sep[k];
				k++;
			}
			dest[j+k] = '\0';
		}
	}
	return (dest);
}

char	*ft_strjoin(int size, char **strs, char *sep)
{
	int		length;
	char	*str;
	if (size == 0)
    {
        str = (char *)malloc(1);
        *str = '\0';
        return str;
    }
    length = 0;
	length = ft_total_len(strs, size) + (size - 1) * ft_strlen(sep);
	str = (char *) malloc((length+1) * sizeof(char));
	if (str == NULL)
        return NULL;
	str = ft_idobigjobs(str, strs, sep, size);
	return (str);
}

int main()
{
    char strings[7][7] = {"hello", "good", "morning", "today", "is a", "great"};
    char **strgs = (char **)strings;
    char spacethem[4] = " % ";
    printf("%s", ft_strjoin(6, strgs, spacethem));

    return 0;
}