在C字符串填充 [英] String Padding in C

查看:372
本文介绍了在C字符串填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这个函数,应该做的StringPadRight(你好,10,0) - >Hello00000

I wrote this function that's supposed to do StringPadRight("Hello", 10, "0") -> "Hello00000".

char *StringPadRight(char *string, int padded_len, char *pad) {
    int len = (int) strlen(string);
    if (len >= padded_len) {
        return string;
    }
    int i;
    for (i = 0; i < padded_len - len; i++) {
        strcat(string, pad);
    }
    return string;
}

它的工作原理,但有一些奇怪的副作用......其他一些变量得到改变。我该如何解决这个问题?

It works but has some weird side effects... some of the other variables get changed. How can I fix this?

推荐答案

这可能有助于知道的printf做填充你,用-10s%作为格式字符串将键盘输入正确的字段中的10个字符长

It might be helpful to know that printf does padding for you, using %-10s as the format string will pad the input right in a field 10 characters long

printf("|%-10s|", "Hello");

将输出

|Hello     |

在这种情况下, - 符号表示左对齐,则10的装置,在字段十字符和S意味着你对准串

In this case the - symbol means "Left align", the 10 means "Ten characters in field" and the s means you are aligning a string.

printf类型的格式在许多语言版本,有很多在网络上引用。这里是多页之一解释格式化标志。像往常一样维基百科的printf页面是帮助过(主要是如何广泛的printf为S $一堂历史课p $垫)。

Printf style formatting is available in many languages and has plenty of references on the web. Here is one of many pages explaining the formatting flags. As usual WikiPedia's printf page is of help too (mostly a history lesson of how widely printf has spread).

这篇关于在C字符串填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆