golang 字符串拼接 数组转化为字符串 Array => String strings.Join Array.prototype.join implode

* strings.join

// Join concatenates the elements of a to create a single string. The separator string
// sep is placed between elements in the resulting string.
func Join(a []string, sep string) string {
	switch len(a) {
	case 0:
		return ""
	case 1:
		return a[0]
	case 2:
		// Special case for common small values.
		// Remove if golang.org/issue/6714 is fixed
		return a[0] + sep + a[1]
	case 3:
		// Special case for common small values.
		// Remove if golang.org/issue/6714 is fixed
		return a[0] + sep + a[1] + sep + a[2]
	}
	n := len(sep) * (len(a) - 1)
	for i := 0; i < len(a); i++ {
		n += len(a[i])
	}

	b := make([]byte, n)
	bp := copy(b, a[0])
	for _, s := range a[1:] {
		bp += copy(b[bp:], sep)
		bp += copy(b[bp:], s)
	}
	return string(b)
}

* join.c

#include <stdio.h>
#include <stdlib.h>

size_t len(char *s) {
  char *p = s;
  size_t len = 0;
  while (*p++ != '\0') {
    ++len;
  }
  return len;
}

size_t ncopy(char *dst, char *src, size_t n) {
  int i = 0;
  while (n-- && (*dst++ = *src++)) { i++; }
  return i;
}

char *join(char **s, size_t l, char *sep) {
  char *r = (char *)0;
  int n = 0, i, j;
  switch (l) {
  case 0:
    r = (char *)malloc(sizeof(char));
    r[0] = '\0';
    return r;
  case 1:
    n = len(s[0]) * sizeof(char) + 1;
    r = (char *)malloc( n );
    ncopy(r, s[0], n);
    return r;
  }
  n = len(sep) * (l-1);
  for (i = 0; i < l; i++) {
    n += len(s[i]);
  }
  r = (char *)malloc(sizeof(char)*n + 1);
  ncopy(r, s[0], len(s[0]));

  int f = 0, h = len(sep);
  for (i = 1, j = len(s[0]); i < l; i++) {
    /* copy separator */
    ncopy(&r[j], sep, h);
    j += h;
    /* copy array elememts */
    f = len(s[i]);
    ncopy(&r[j], s[i], f);
    j += f;
  }
  r[n*sizeof(char)] = '\0';
  return r;
}

int main(int argc, char **argv) {
  printf("%lu\n", len("Hello, world!"));

  char *a[3] = {"He", "ll", "o"};
  char *s = join(a, sizeof(a)/sizeof(a[0]), "::");
  printf("%s\n", s);
  free(s);

  char *b[1] = {"world"};
  printf("%s\n", (s = join(b, 1, ",")));
  free(s);

  char *c[5] = {"a", "b", "c", "d", "e"};
  printf("%s\n", (s = join(c, 5, ",")));
  free(s);

  char *d[4] = {"12","345", "6", "789"};
  printf("%s\n", (s = join(d, 4, "")));
  free(s);
  
  return 0;
}

* compile

gcc join.c -Wall

* run

./a.out

13

He::ll::o

world

a,b,c,d,e

123456789

猜你喜欢

转载自blog.csdn.net/fareast_mzh/article/details/84674528