Is there a built-in method to pad a string? - dart

I'm trying to add zero-padding to a number. I did some searching and can't find an obvious way to do this. Am I missing something?

Dart 1.3 introduced a String.padLeft and a String.padRight you can use :
String intToString(int i, {int pad 0}) => i.toString().padLeft(pad, '0');

You can use the String function .padLeft(Int width, [String = ' '])
https://api.dartlang.org/apidocs/channels/dev/dartdoc-viewer/dart-core.String#id_padLeft
int i = 2;
print(i.toString().padLeft(2, "0"));
result: 02

I don't think you're missing anything, there's a big lack of formatting functions right now. I think the best you can do is something like:
String intToString(int i, {int pad: 0}) {
var str = i.toString();
var paddingToAdd = pad - str.length;
return (paddingToAdd > 0)
? "${new List.filled(paddingToAdd, '0').join('')}$i" : str;
}
Obviously something that took a format string would be much nicer. Feature request?

Related

How to convert a unicode hex string into its ASCII equivalent

I hope everything is going well.
I have this unicodestring:
353135313531353135313531
And I want to transform it into another unicodestring with this content:
515151515151
In other words, convert a hex representation into its ASCII interpretation.
It is very straightforward to do this in C, but the idea is to work with C++ Builder.
This is what I have been trying to do:
String hex_to_ascii(const String& hex_str) {
String ascii_str = "";
for (int i = 1; i <= hex_str.Length(); i += 2) {
String hex_char = hex_str.SubString(i, 2);
int ascii_char = hex_char.ToInt();
// ascii_str += String().sprintf(_D("%c"), ascii_char);
ascii_str.Insert(ascii_char, ascii_str.Length() + 1);
}
return ascii_str;
But no luck so far.
I know there is a method called ToHex I've been trying to search for documentation about it because it's related to what I am trying to do, so probably the library that has this method has also something close to what I need.
If you know how to do this or where can I read about the ToHex method, please let me know. Thank you for reading.
The code you have is very close, it just needs some minor tweaks.
Most importantly, String::ToInt() WILL NOT decode hex, like you are expecting. It will convert "35" to an integer with a value of decimal 35 (NOT hex 0x35, decimal 53), and will convert "31" to an integer with a value of decimal 31 (NOT hex 0x31, decimal 49), etc.
You need to instead use Sysutils::StrToInt() with a 0x hex prefix prepended to the string value.
Try this:
String hex_to_ascii(const String& hex_str) {
String ascii_str;
for (int i = 1; i <= hex_str.Length(); i += 2) {
String hex_char = _D("0x") + hex_str.SubString(i, 2);
int ascii_char = StrToInt(hex_char);
ascii_str += static_cast<Char>(ascii_char);
}
return ascii_str;
}
Alternatively, you can use HexToBin() to decode the hex into a byte array, and then construct a UnicodeString from those bytes, eg:
String hex_to_ascii(const String& hex_str) {
TBytes bytes;
bytes.Length = hex_str.Length() / 2;
HexToBin(hex_str.c_str(), &bytes[0], bytes.Length);
return String((char*)&bytes[0], bytes.Length);
// Alternatively:
// return TEncoding::Default.GetString(bytes);
}

String of fixed length digits in Bogus

I did this:
var f = new Faker();
String.Join("", f.Random.Digits(10)
However, is there another method that would eliminate the 'Join' call?
Wow. Sorry for the late reply, but yes there's a way to do this in Bogus.
void Main()
{
var f = new Faker();
var numberString = f.Random.ReplaceNumbers("##########");
numberString.Dump();
}
OUTPUT:
2166951396
By the way, thanks for using Bogus!

String formatting in Dart

I was looking up string classes and some other resources, trying to see how to format strings. Primarily, I am trying to Pad out a number to a string, but not precision.
example:
int a = 0, b = 5, c = 15, d = 46;
String aout = "", bout = "", cout="", dout="";
//aout = "00"
//bout = "05"
//cout = "15"
//dout = "46"
When i was looking at int to fixed string precision, it was mostly when dealing with decimals and not prepended padding.
My original thought is that I could do something related to sprintf, such as:
String out = sprintf("%02d", a);
but that didnt seem to work, mostly because It was saying that i am getting a nosuchmethod error. I was not sure if sprintf is in a different package other than core, as i thought this would be related directly to strings.
There's a String.padLeft method you can use:
String out = a.toString().padLeft(2, '0');

ParseInt Processing

Can someone help me to understand why if my val value is a "0" Integer.parseInt(val) returns me NumberFormatException and if i write Integer.parseInt("0") it works correctly...
There's a way easier to work directly with the int value read from Serial?
void draw(){
i=0;
byte[] str = new byte[5];
if ( myPort.available() > 0)
{
myPort.readBytesUntil(10, inBuffer);
if(inBuffer==null){
//...
}
else
{
while(inBuffer[i]!=13){
str[i]=inBuffer[i];
println((int)str[i]);
i++;
}
String val = new String(str);
i = Integer.parseInt(val);
println(i);
}
}
}
In Processing port.readBytesUntil(ch, buffer) reads all characters from port until encounter character equal to ch.
In Windows line separator is composed from 2 characters (0d,0a) or (13,10).
So if you write to serial "23", next newline, next "45", etc., the buffer will look like this:
char[] buffer : '2', '3', '0x0d', '0x0a', '4', '5', '0x0d', '0x0a', ...
So when you readBytesUntil(10, ...) it read 3 characters: '2', '3', '0x0d'.
Consider such example:
char[] c = {'2', '3', 13};
String str = new String(c);
System.out.println(str); // you will see "23"
System.out.println(str.length()); // lenght will be 3
System.out.println(Integer.parseInt(str.trim())); // will be OK
System.out.println(Integer.parseInt(str)); // will throw NumberFormatException
So try to convert your buffer to String and trim() this string.
== EDIT ==
Processing gives you some convenience methods such as:
String str = port.readStringUntil(10);
str = str.trim();
Can you provide an MCVE that demonstrates the problem? Use hardcoded values and keep it as simple as possible, like this:
void setup(){
String val = "0";
int i = Integer.parseInt(val);
println(i);
}
Print out the value of val before you try parsing it. I would bet it's not the value you think it is.

Extract More than 3 Words After the First Word

In the app I'm working on, I need to extract the first word from a String and put it into another String and the rest of the words in yet another String. I was able to extract the first word using:
String pString = "KOF0000094 Implementation:ListingRequest:User FO-Partner"
int spacePos3 = pString.indexOf(" ");
String pFirstWord = pString.substring(0,spacePos3);
Result : KOF0000094
Now I want the "Implementation:ListingRequest:User FO-Partner" to put
in another String.
Thanks for your help in advance
Simplest solution with what you already have.
String restOfString = pString.substring(spacePos3+1)
String pSecondWord = pString.substring(spacePos3 + 1);
String whole = "KOF0000094 Implementation:ListingRequest:User FO-Partner";
String firstWord = "";
String restOfWords = "";
int spacesIndex = whole.indexOf(" ", 0);
restOfWords = whole.substring(spacesIndex, whole.length());
restOfWords = restOfWords.trim();
firstWord = whole.substring(0, spacesIndex);
firstWord = firstWord.trim();
This is simple string parsing... just find the first index of the first space... i.e. in a for loop...
if(string.charAt(i) == Characters.SPACE)
indexOfSpace = i;
Then your first word will be
String part1 = string.substring(0,indexOfSpace);
and the second string will be
String part2 = string.substring(indexOfSpace + 1);
Try using another call to substring(). What is the index of the first character in the string you want? What is the index of the last character?
You already have the index of the first space, which marks the end of the first word, so all you need to do is take the substring from the index immediately after that (so you don't include the space itself) to the end of the string.
You're probably better of using the split function
It would look something like this:
String pString = "KOF0000094 Implementation:ListingRequest:User FO-Partner";
String[] parts = pString.split(" ");
String partone = parts[0];
String partwo = parts[1] + " " +parts[2];
Or something similar, if there are going to be more spaces in the part following the first word you could use a loop or something similar;
You could use split, for instance...
static String pString = "KOF0000094 Implementation:ListingRequest:User FO-Partner";
static String[] pFirstWord = pString.split(" ");
/**
* #param args
*/
public static void main(String[] args) {
for(String word : pFirstWord) {
System.out.println(word);
}
}
This returned...
KOF0000094
Implementation:ListingRequest:User
FO-Partner
So the last string would be pFirstWord[1] + pFirstWord[2]
String class has a split method: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#split(java.lang.String)
Use that if you want to get all the words.
EDIT: as mentioned in the comments, String.split is not supported in BB Java.
Or this if you just want the first word and the rest of the string:
int index=yourstring.indexOf(" ");
String firstWord = yourstring.substring(0,index);
String rest = yourstring.substring(index+1);

Resources