输出中的逗号分隔

如何在1000,10000,100000,1000000之类的输入中给出的数字的数字之间得到逗号,并将数字的数字分开,例如1,000 10,000 100,000 1,000,000作为输出

C中的任何函数(库)是否为此创建程序?

使用非标准'打印标志和设置区域设置:

 #include  #include  int main() { int value = 1234567; if (!setlocale(LC_ALL, "en_US.UTF-8")) { fprintf(stderr, "Locale not found.\n"); return 1; } printf("%'d\n", value); return 0; } 

但是使用x mod 3和Duff的设备,你可以构建自己的(便携式)function:

 #include  #include  char *thousand_sep(long x) { char s[64], *p = s, *q, *r; int len; len = sprintf(p, "%ld", x); q = r = malloc(len + (len / 3) + 1); if (r == NULL) return NULL; if (*p == '-') { *q++ = *p++; len--; } switch (len % 3) { do { *q++ = ','; case 0: *q++ = *p++; case 2: *q++ = *p++; case 1: *q++ = *p++; } while (*p); } *q = '\0'; return r; } int main(void) { char *s = thousand_sep(1234567); printf("%s\n", s); free(s); return 0; } 

输出:

 1,234,567 

编辑:

如果我想在java中做同样的话??

对不起,我不懂Java,也许有用(在javascript中使用正则表达式):

 Number.prototype.thousand_sep = function(decs){ var n = this.toFixed(decs).toString().split('.'); n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ','); return n.join('.'); }; ... var x = 1234567; alert(x.thousand_sep(0)); 
  • 对于输入,由您自己决定只读取逗号分隔的整数。 我会使用strtol()并手动跳过逗号。
  • 对于输出,添加'到正确的printf()输出说明符,即printf("%'d", 1000); 应该将int1000打印为1,000 。 这取决于您的区域设置, 有关详细信息 ,请参见手册页 。

对于java(在某处注释中由OP询问),请使用:

 String formattedString = NumberFormat.getInstance().format(number); 

如果您需要特定的区域设置:

 String formattedString = NumberFormat.getInstance(Locale.FRENCH).format(number); 

如果您需要其他数字格式化程序(货币,百分比等):

 NumberFormat.getCurrencyInstance().format(number); NumberFormat.getIntegerInstance().format(number); NumberFormat.getPercentInstance().format(number); 

[他们每个人都可以通过Locale传递给]

要更好地控制格式化选项,您可以切换到DecimalFormat :

 new DecimalFormat("0,000.00").format(number); 

我建议你探索这两个类(NumberFormat和DecimalFormat)来理解你的可能性。

我找不到任何可以解决这个问题的库。

我已经编写了一些代码来执行所需的操作。

 #include "stdio.h" #include "string.h" void func (int in, char * modified_int) { char my_int[1000]; sprintf (my_int, "%d", in); int len = strlen(my_int); int curr_index = len + len/3 - 1; modified_int[curr_index+1] = '\0'; int modulo_3 = 0; for (int i = len-1; i >= 0; i--, curr_index--, modulo_3++) { char abc = my_int[i]; modified_int[curr_index] = abc; if ((modulo_3 == 2) && (i != 0)) { curr_index--; modified_int[curr_index] = ','; modulo_3 = -1; } } } int main () { char my_int[1000]; int n = 1000; func(n, my_int); printf("%s\n", my_int); return 0; } 

如果它无法解决您的问题,请告诉我。