题
请您告诉我下面的C ++代码片段相当于BASH代码会是什么:
std::cout << std::setfill('x') << std::setw(7) << 250;
的输出是:
xxxx250
感谢您的帮助!
解决方案
如果你是在Linux上,它只是这个目的的printf
程序。其他UNIX变体也可以具有它。
填充数字与x
是不是真的就其使用情况,但你可以用得到相同的结果:
pax> printf "%7d\n" 250 | tr ' ' 'x'
xxxx250
,其输出250空间填充,然后使用tr
翻译工具把这些空间成x
字符。
如果你正在寻找一个只bash
的解决方案,你可以启动:
pax> n=250 ; echo ${n}
250
pax> n=xxxxxxx${n} ; echo ${n}
xxxxxxx250
pax> n=${n: -7} ; echo ${n}
xxxx250
如果你想要的一般化的解决方案,则可以使用此功能fmt
,单元测试代码包含:
#!/bin/bash
#
# fmt <string> <direction> <fillchar> <size>
# Formats a string by padding it to a specific size.
# <string> is the string you want formatted.
# <direction> is where you want the padding (l/L is left,
# r/R and everything else is right).
# <fillchar> is the character or string to fill with.
# <size> is the desired size.
#
fmt()
{
string="$1"
direction=$2
fillchar="$3"
size=$4
if [[ "${direction}" == "l" || "${direction}" == "L" ]] ; then
while [[ ${#string} -lt ${size} ]] ; do
string="${fillchar}${string}"
done
string="${string: -${size}}"
else
while [[ ${#string} -lt ${size} ]] ; do
string="${string}${fillchar}"
done
string="${string:0:${size}}"
fi
echo "${string}"
}
# Unit test code.
echo "[$(fmt 'Hello there' r ' ' 20)]"
echo "[$(fmt 'Hello there' r ' ' 5)]"
echo "[$(fmt 'Hello there' l ' ' 20)]"
echo "[$(fmt 'Hello there' l ' ' 5)]"
echo "[$(fmt 'Hello there' r '_' 20)]"
echo "[$(fmt 'Hello there' r ' .' 20)]"
echo "[$(fmt 250 l 'x' 7)]"
这个输出:
[Hello there ]
[Hello]
[ Hello there]
[there]
[Hello there_________]
[Hello there . . . . ]
[xxxx250]
和你不仅限于它们打印,也可以保存以供日后变量用线,如:
formattedString="$(fmt 'Hello there' r ' ' 20)"
其他提示
可以打印填充这样的:
printf "x%.0s" {1..4}; printf "%d\n" 250
如果你想概括,不幸的是你必须使用eval
:
value=250
padchar="x"
padcount=$((7 - ${#value}))
pad=$(eval echo {1..$padcount})
printf "$padchar%.0s" $pad; printf "%d\n" $value
可以直接在支架序列表达式中的ksh使用变量,而不是击。
s=$(for i in 1 2 3 4; do printf "x"; done;printf "250")
echo $s
不隶属于 StackOverflow