C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Input file:
2 - pa
2 - zo
23 - zo
3 - ad
3 - za
Required output:
2 - pa
2 - zo
3 - ad
3 - za
23 - zo
And: The Line object implements IComparable: in CompareTo, it first compares the integer fields and then the characters following.
IComparableToStringStreamReaderC# program that sorts strings with numbers
using System;
using System.Collections.Generic;
using System.IO;
class Line : IComparable<Line>
{
int _number;
string _afterNumber;
string _line;
public Line(string line)
{
// Get leading integer.
int firstSpace = line.IndexOf(' ');
string integer = line.Substring(0, firstSpace);
this._number = int.Parse(integer);
// Store string.
this._afterNumber = line.Substring(firstSpace);
this._line = line;
}
public int CompareTo(Line other)
{
// First compare number.
int result1 = _number.CompareTo(other._number);
if (result1 != 0)
{
return result1;
}
// Second compare part after number.
return _afterNumber.CompareTo(other._afterNumber);
}
public override string ToString()
{
return this._line;
}
}
class Program
{
static void Main()
{
List<Line> list = new List<Line>();
using (StreamReader reader = new StreamReader("c:\\p.txt"))
{
while (true)
{
string line = reader.ReadLine();
if (line == null)
{
break;
}
list.Add(new Line(line));
}
}
list.Sort();
foreach (Line value in list)
{
Console.WriteLine(value);
}
}
}
Output
2 - pa
2 - zo
3 - ad
3 - za
23 - zo
Note: The solution presented above makes many things possible by actually storing the integer as a field.
Thus: In the C# language, implementing the IComparable interface and using a custom constructor is one approach that succeeds.