Sorting an Array

gogamza madjakarta at gmail.com
Tue Jul 10 08:37:02 PDT 2007


okibi Wrote:

> Is there an easy way to sort an array with elements such as "12 - Some text" or "241 - Other Text"?
> 
> I want to sort in order of the numbers. Is this possible?
> 
> Thanks!


how about this method?


---------------------------------------------------------------------------------------------------
import std.stdio;
import std.string;
import std.conv;

struct keyvalue{
	char[] str;
	
	int opCmp(keyvalue* s){
		char[][] paramKV = split(s.str, "-");
		char[][] thisKV = split(this.str, "-");		
		return toInt(thisKV[0]) - toInt(paramKV[0]);
	}
}



void main(){
	static keyvalue keyval = {"12-Some text"};
	static keyvalue keyval2 = {"6-Other Text"};
	static keyvalue keyval3 = {"7-Other Text2"};

	keyvalue[] keyvals = [keyval, keyval2, keyval3];

	keyvalue[] keyvals2 = keyvals.sort;

	foreach(keyvalue kv;keyvals2){
		writefln(kv.str);
	}
}

----------------------------------------------------------------------------------------------------




More information about the Digitalmars-d-learn mailing list