Formatted output ranges

Dennis Ritchie via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Apr 11 18:56:58 PDT 2015


On Saturday, 11 April 2015 at 22:45:39 UTC, Dennis Ritchie wrote:
> I also want to know whether it is possible to D somehow set the 
> maximum width of the print string in characters?

I got to do this:

-----
import std.stdio, std.range, std.conv, std.array;

void formatWidthIotaToStr(ref string formatStr, int[] inputRange) 
{
	
	formatStr ~= ";;";
	int formatWidth = 30, lenStr = formatStr.length;
	
	foreach (e; inputRange) {
		lenStr += e.text.length;
		if (lenStr < formatWidth) {
			lenStr += 2;
			formatStr ~= ' ', formatStr ~= e.text, formatStr ~= ',';
		}
		else {
			formatStr ~= "\n;; ", formatStr ~= e.text, formatStr ~= ',';
			lenStr = e.text.length + 5;
		}
	}
	
	formatStr.length -= 1;
	formatStr ~= '.';
}

void main() {
	
	auto a = iota(10, 1101).array;
	
	string s;
	
	formatWidthIotaToStr(s, a);
	
	writeln(s);
}
-----
http://ideone.com/Yoohbk


More information about the Digitalmars-d-learn mailing list