How to pad a number with zeros when printing? - go

How can I print a number or make a string with zero padding to make it fixed width?
For instance, if I have the number 12 and I want to make it 000012.

The fmt package can do this for you:
fmt.Printf("|%06d|%6d|\n", 12, 345)
Output:
|000012| 345|
Notice the 0 in %06d, that will make it a width of 6 and pad it with zeros. The second one will pad with spaces.
Try it for yourself here: http://play.golang.org/p/cinDspMccp

Use the Printf function from the fmt package with a width of 6 and the padding character 0:
import "fmt"
fmt.Printf("%06d", 12) // Prints to stdout '000012'
Setting the width works by putting an integer directly preceding the format specifier ('verb'):
fmt.Printf("%d", 12) // Uses default width, prints '12'
fmt.Printf("%6d", 12) // Uses a width of 6 and left pads with spaces, prints ' 12'
The only padding characters supported by Golang (and most other languages) are spaces and 0:
fmt.Printf("%6d", 12) // Default padding is spaces, prints ' 12'
fmt.Printf("%06d", 12) // Change to 0 padding, prints '000012'
It is possible to right-justify the printing by prepending a minus -:
fmt.Printf("%-6d", 12) // Padding right-justified, prints '12 '
Beware that for floating point numbers the width includes the whole format string:
fmt.Printf("%06.1f", 12.0) // Prints '0012.0' (width is 6, precision is 1 digit)
It is useful to note that the width can also be set programmatically by using * instead of a number and passing the width as an int parameter:
myWidth := 6
fmt.Printf("%0*d", myWidth, 12) // Prints '000012' as before
This might be useful for instance if the largest value you want to print is only known at runtime (called maxVal in the following example):
myWidth := 1 + int(math.Log10(float64(maxVal)))
fmt.Printf("%*d", myWidth, nextVal)
Last, if you don't want to print to stdout but return a String, use Sprintf also from fmt package with the same parameters:
s := fmt.Sprintf("%06d", 12) // returns '000012' as a String

There is one simplest way to achieve this. Use
func padNumberWithZero(value uint32) string {
return fmt.Sprintf("%02d", value)
}
fmt.Sprintf formats and returns a string without printing it anywhere.
Here %02d says pad zero on left for value who has < 2 number of digits. If given value has 2 or more digits it will not pad. For example:
If input is 1, output will be 01.
If input is 12, output will be 12.
If input is 1992, output will be 1992.
You can use %03d or more for more zeros padding.

Just in case if you want to prefix or suffix to form another word by concatenating you can use below code.
package main
import "fmt"
func main() {
concatenatedWord:= "COUNTER_"+fmt.Sprintf("%02d", 1)
// use concatenatedWord
fmt.Println("ConcatenatedWordword is", concatenatedWord)
}
output : ConcatenatedWordword is COUNTER_01
link : https://play.golang.org/p/25g3L8TXiPP

The question "List of printing format in Go lang" reminds us that there is also the flag:
- pad with spaces on the right rather than the left (left-justify the field)
You can see more padding examples with DaddyOh/golang-samples/pad.go, if you want to pad with other string sequences (more complex than '0' or ''):
leftPad(s string, padStr string, pLen int)
rightPad(s string, padStr string, pLen int)
leftPad2Len(s string, padStr string, overallLen int)
rightPad2Len(s string, padStr string, overallLen int)
See play.golang.org:
1234567890
leftPad(str, "*", 3) ***1234567890
leftPad2Len(str, "*-", 13) -*-1234567890
leftPad2Len(str, "*-", 14) *-*-1234567890
leftPad2Len(str, "*", 14) ****1234567890
leftPad2Len(str, "*-x", 14) x*-x1234567890
leftPad2Len(str, "ABCDE", 14) BCDE1234567890
leftPad2Len(str, "ABCDE", 4) 7890
rightPad(str, "*", 3) 1234567890***
rightPad(str, "*!", 3) 1234567890*!*!*!
rightPad2Len(str, "*-", 13) 1234567890*-*
rightPad2Len(str, "*-", 14) 1234567890*-*-
rightPad2Len(str, "*", 14) 1234567890****
rightPad2Len(str, "*-x", 14) 1234567890*-x*
rightPad2Len(str, "ABCDE", 14) 1234567890ABCD
rightPad2Len(str, "ABCDE", 4) 1234

func lpad(s string,pad string, plength int)string{
for i:=len(s);i<plength;i++{
s=pad+s
}
return s
}
lpad("3","0",2) result: "03"
lpad("12","0",6) result: "000012"

Here's my solution:
func leftZeroPad(number, padWidth int64) string {
return fmt.Sprintf(fmt.Sprintf("%%0%dd", padWidth), number)
}
Example usage:
fmt.Printf("%v", leftZeroPad(12, 10))
prints:
0000000012
The advantage of this is that you can specify the pad length at run time if needed.

For those that want to right pad, you can do this:
str2pad := "12"
padWith := "0"
amt2pad := 6
//This will make sure there is always 6 characters total, padded on the right side
//Note to check if strings.Repeat returns a negative value
paddedStr := str2pad + strings.Repeat(padWith, amt2pad - len(str2pad))
//Outputs 120000

Another option is the golang.org/x/text/number package:
package main
import (
"golang.org/x/text/language"
"golang.org/x/text/message"
"golang.org/x/text/number"
)
var fmt = message.NewPrinter(language.English)
func main() {
n := number.Decimal(
12, number.Pad('0'), number.FormatWidth(6),
)
fmt.Println(n) // 000012
}
https://pkg.go.dev/golang.org/x/text/number

fmt.Printf("%012s", "345")
Result: 000000000345

Related

Replace decimal numbers in string by hex equivalent

I have a huge set of strings like:
// Register 10:
typedef struct RegAddr_10
{
uint8 something: 4;
uint8 something_else: 4;
} tRegAddr_10;
and want to convert all register addresses (given in decimal numbers) to hexadecimal. Other numbers can occur within each typedef; therefore I have to consider the Reg part as a kind of delimiter. The example should result in:
// Register 0x0A:
typedef struct RegAddr_0x0A
{
uint8 something: 4;
uint8 something_else: 4;
} tRegAddr_0x0A;
My solution is this:
class String
def convert_base(from, to)
self.to_i(from).to_s(to)
end
end
new = text.gsub(/Reg\D*\d*/) do |number|
number.gsub(/(\d+)/) {'0x'+$1.convert_base(10,16)}
end
It works, but:
(How) is it possible to do this with one gsub only?
How can I make the conversion generate 2-digit-hex numbers in upper case, e.g. 10 → 0x0A, not 0xa?
Code
R = /
(?: # begin non-capture group
^ # match beginning of line
\/{2}\s+Register\s+ # match string
| # or
\s+RegAddr_ # match string
| # or
\s+tRegAddr_ # match string
) # close non-capture group
\K # discard everything matched so far
\d+ # match >= 1 digits
/x # extended mode
def replace_with_hex(str)
str.gsub(R) { |s| "0x%02X" % s }
end
The part of the format string for String#% that follows the percent character is: 0, meaning pad left with zeros, 2 for field width and X to convert to hex with letters A-F in capitals (x for lower case).
Example
str = <<_
// Register 10:
typedef struct RegAddr_10
{
uint8 something: 4;
uint8 something_else: 4;
} tRegAddr_10;
_
puts replace_with_hex(str)
prints:
// Register 0x0A:
typedef struct RegAddr_0x0A
{
uint8 something: 4;
uint8 something_else: 4;
} tRegAddr_0x0A;
Alternatives
If you are less fussy:
R = /
[\s|t] # match whitespace or t
Reg\D+ # match string
\K # discard everything matched so far
\d+ # match >= 1 digits
/x # extended mode
works as well.
You could also change the operative line of replace_with_hex to:
str.gsub(R, "0x%02X" % $~[0])

New syntax for default values in Swift functions

I just noticed that the latest beta of Xcode (7.1) has changed the signature for the print function in Swift.
The new syntax is:
public func print(items: Any..., separator: String = default, terminator: String = default)
Anybody knows what this default thing is? How do you specify the default value, not just the fact that it has one?
The default in the function signature means that it has a default value and you don't have to pass a parameter.
func add(a: Int = 0, b: Int = 0) -> Int {
return a + b
}
// "normal" function call
add(2, b: 4) // 6
// no specified parameters at all
add() // 0; both a and b default to 0
// one parameter specified
// a has no external name since it is the first parameter
add(3) // 3; b defaults to 0
// b has an external name since it is not the first parameter
add(b: 4) // 4; a defaults to 0
In case of the print function separator defaults to " " and terminator to "\n".
There are 4 way to call it:
struct SomeItem {}
print(SomeItem(), SomeItem())
print(SomeItem(), SomeItem(), separator: "_")
print(SomeItem(), SomeItem(), terminator: " :) \n")
print(SomeItem(), SomeItem(), separator: "_", terminator: " :) \n")
Prints:
SomeItem() SomeItem()
SomeItem()_SomeItem()
SomeItem() SomeItem() :)
SomeItem()_SomeItem() :)
the default separator is a single space, and the default terminator is a newline
to use a different value for either of these, simply pass the desired value as an argument when you call the function - e.g.:
print("first", "second", separator: "-", terminator: "...")
print("third")
// => "first-second...third"

Swift adding multiple stringByReplacingOccurrencesOfString on one String?

Hello i would like to create a app that changes characters into binary code and i was wondering if there is a way to add multiple stringByReplacingOccurrencesOfString on one String or if i should take another approach to this "Problem".
Here is what i have so far
func textToBinary(theString: String) -> String {
return theString.stringByReplacingOccurrencesOfString("a",
withString: "01100001")
}
textArea.text = textToBinary(lettersCombined)
// lettersCombined is the string that i want to turn into BinaryCode.
Try this:
func textToBinary(theString : String, radix : Int = 2) -> String {
var result = ""
for c in theString.unicodeScalars {
result += String(c.value, radix: radix) + " "
}
return result
}
println(textToBinary("a"))
println(textToBinary("abc", radix: 10))
println(textToBinary("€20", radix: 16))
println(textToBinary("😄"))
(The last one is a smiley face but somehow my browser can't display it).
Edit: if you want to pad your strings to 8-character long, try this:
let str = "00000000" + String(c.value, radix: radix)
result += str.substringFromIndex(advance(str.startIndex, str.characters.count - 8)) + " "
The first line adds eight 0 the left of your string. The second line takes the last 8 characters from the padded string.

How do I get the line and column number of a character at some index in Text View?

I have a NSTextView in which I have lots of text.
How can I get the line and the column number of the character at some index?
Lets say, I have this text in the NSTextView:
"This is just a\ndummy text\nto show you\nwhat I mean."
And I need the line and column number for the 16th character. In this case:
Line: 2
Column: 2
How can I calculate/get this using Swift?
Another example:
"This is just a\ndummy text\nto show you\nwhat I mean."
And I want the line and row number for 15th (or 16th, if \n are counted too) character, like this:
Line: 2
Column: 1
You just need to break your text lines using String method componentsSeparatedByString, then you just need to keep count of your lines, columns and character position as follow:
extension String {
func characterRowAndLineAt(position: Int) -> (character: String, line: Int, column:Int)? {
var lineNumber = 0
var characterPosition = 0
for line in components(separatedBy: .newlines) {
lineNumber += 1
var columnNumber = 0
for column in line {
characterPosition += 1
columnNumber += 1
if characterPosition == position {
return (String(column), lineNumber, columnNumber )
}
}
characterPosition += 1
if characterPosition == position {
return ("\n", lineNumber, columnNumber+1 )
}
}
return nil
}
}
let myText = "This is just a\ndummy text\nto show you\nwhat I mean."
let result = myText.characterRowAndLineAt(position: 16) // "(.0 "d", .1 2, .2 1)"
let character = result?.character // "d"
let line = result?.line // 2
let column = result?.column // 1

What's in xcode console with scanf ,when want a number but input a char?

xcode 5.0
when I run following code:
void guessNum(){
int answer = 0;
int guess = 0;
int turn = 0;
answer = arc4random() % 100 + 1;
while (guess != answer) {
turn++;
NSLog(#"Guess #%i: Enter a number between 1 and 100", turn);
scanf("%i", &guess);
if (guess > answer) {
NSLog(#"Lower!");
}
else if (guess < answer) {
NSLog(#"Higher!");
}
else {
NSLog(#"Correct! The answer was %i", answer);
}
} // end of while loop
NSLog(#"It took you %i tries", turn);
}
when I type a character, just like a in xcode debug console, program run automatic and print:
...
2013-11-18 10:47:39.719 donglix[15115:303] Higher!
2013-11-18 10:47:39.719 donglix[15115:303] Guess #1932: Enter a number between 1 and 100
2013-11-18 10:47:39.719 donglix[15115:303] Higher!
2013-11-18 10:47:39.720 donglix[15115:303] Guess #1933: Enter a number between 1 and 100
...
what's the problem?
"scanf()" reads the input you've typed in and, because of your "%i" (integer) format string, is expecting to take that input and drop it into a number.
If you used "%s" as your format string, then you would take the input as a C-style character array (and have to convert those characters if you wanted to get the integer value out of that).
For example, you can replace this line:
scanf("%i", &guess);
with something like this:
char stringToConvert[256]; // if you type more than 256 characters, you'll crash
sscanf("%s",&stringToConvert);
guess = atoi(stringToConvert); // this function converts the string into an integer
If you type in the character "a", scanf converts that to 97 in the ascii table.

Resources