Windows Phone character-encoding - character-encoding

My code is Encoding.GetEncoding("iso-8859-9"); in my Windows Phone project. But "iso-8859-9" is not supported on Windows Phone. How can I fix this problem?
http://www.hardcodet.net/2010/03/silverlight-text-encoding-class-generator
I also found this link but I don't know how to use it.

To use the program, just type the encoding name and it will generate the class like so:
Then make a file for the class somewhere (Copypaste the code generated from the program) and start using it:
//Instead of
Encoding enc = Encoding.GetEncoding("iso-8859-9");
//do this
Encoding enc = new ISO88599Encoding();
//Proceed exactly the same
The code generated is too long to copypaste here but hopefully you manage with these instructions.

Here is a piece of code that is Windows Phone 7.1 (and Silverlight I think) compatible that redefines an ISO-8859-9 (or Latin9) encoding. The code also redefines the ISO-8859-1 (or Latin1) and Windows-1252 for convenience. It could also be used to define the other ISO Latin encoding family:
public class Latin9Encoding : LatinEncoding
{
public Latin9Encoding()
: base(CharMap)
{
}
static Latin9Encoding()
{
CharMap = new Dictionary<byte, char>();
CharMap.Add(0xD0, '\u011E');
CharMap.Add(0xDD, '\u0130');
CharMap.Add(0xDE, '\u015E');
CharMap.Add(0xF0, '\u011F');
CharMap.Add(0xFD, '\u0131');
CharMap.Add(0xFE, '\u015F');
}
public static Dictionary<byte, char> CharMap;
public override string WebName
{
get
{
return "iso-8859-9";
}
}
}
public class Windows1252Encoding : LatinEncoding
{
public Windows1252Encoding()
: base(CharMap)
{
}
static Windows1252Encoding()
{
CharMap = new Dictionary<byte, char>();
CharMap.Add(0x80, '\u20AC');
CharMap.Add(0x82, '\u201A');
CharMap.Add(0x83, '\u0192');
CharMap.Add(0x84, '\u201E');
CharMap.Add(0x85, '\u2026');
CharMap.Add(0x86, '\u2020');
CharMap.Add(0x87, '\u2021');
CharMap.Add(0x88, '\u02C6');
CharMap.Add(0x89, '\u2030');
CharMap.Add(0x8A, '\u0160');
CharMap.Add(0x8B, '\u2039');
CharMap.Add(0x8C, '\u0152');
CharMap.Add(0x8E, '\u017D');
CharMap.Add(0x91, '\u2018');
CharMap.Add(0x92, '\u2019');
CharMap.Add(0x93, '\u201C');
CharMap.Add(0x94, '\u201D');
CharMap.Add(0x95, '\u2022');
CharMap.Add(0x96, '\u2013');
CharMap.Add(0x97, '\u2014');
CharMap.Add(0x98, '\u02DC');
CharMap.Add(0x99, '\u2122');
CharMap.Add(0x9A, '\u0161');
CharMap.Add(0x9B, '\u203A');
CharMap.Add(0x9C, '\u0153');
CharMap.Add(0x9E, '\u017E');
CharMap.Add(0x9F, '\u0178');
}
public static Dictionary<byte, char> CharMap;
public override string WebName
{
get
{
return "Windows-1252";
}
}
}
public class Latin1Encoding : LatinEncoding
{
public Latin1Encoding()
: base(null)
{
}
public override string WebName
{
get
{
return "iso-8859-1";
}
}
}
public abstract class LatinEncoding : Encoding
{
protected LatinEncoding(Dictionary<byte, char> map)
{
FallbackByte = (byte)'?';
if (map != null)
{
Map = map;
ReverseMap = new Dictionary<char, byte>(map.Count);
foreach (var entry in map)
{
ReverseMap[entry.Value] = entry.Key;
}
}
}
public byte FallbackByte { get; set; }
public Dictionary<byte, char> Map { get; private set; }
public Dictionary<char, byte> ReverseMap { get; private set; }
public override int GetByteCount(char[] chars, int index, int count)
{
return count;
}
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
if (chars == null)
throw new ArgumentNullException("bytes");
if (charIndex < 0)
throw new ArgumentOutOfRangeException("charIndex");
if (charCount < 0)
throw new ArgumentOutOfRangeException("charCount");
if (bytes == null)
throw new ArgumentNullException("bytes");
if (byteIndex < 0)
throw new ArgumentOutOfRangeException("byteIndex");
if ((charIndex + charCount) > chars.Length)
throw new ArgumentOutOfRangeException("charCount");
if ((byteIndex + charCount) > bytes.Length)
throw new ArgumentOutOfRangeException("charCount");
for (int i = 0; i < charCount; i++)
{
char c = chars[charIndex + i];
if (ReverseMap != null)
{
byte b;
if (ReverseMap.TryGetValue(c, out b))
{
bytes[byteIndex + i] = b;
continue;
}
}
bytes[byteIndex + i] = c > 255 ? FallbackByte : (byte)c;
}
return charCount;
}
public override int GetCharCount(byte[] bytes, int index, int count)
{
return count;
}
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
if (bytes == null)
throw new ArgumentNullException("bytes");
if (chars == null)
throw new ArgumentNullException("chars");
if (byteIndex < 0)
throw new ArgumentOutOfRangeException("byteIndex");
if (byteCount < 0)
throw new ArgumentOutOfRangeException("byteCount");
if (charIndex < 0)
throw new ArgumentOutOfRangeException("charIndex");
if ((byteIndex + byteCount) > bytes.Length)
throw new ArgumentOutOfRangeException("byteCount");
if ((charIndex + byteCount) > chars.Length)
throw new ArgumentOutOfRangeException("byteCount");
for (int i = 0; i < byteCount; i++)
{
if (Map != null)
{
char c;
if (Map.TryGetValue(bytes[byteIndex + i], out c))
{
chars[charIndex + i] = c;
continue;
}
}
chars[charIndex + i] = (char)bytes[byteIndex + i];
}
return byteCount;
}
public override int GetMaxByteCount(int charCount)
{
return charCount;
}
public override int GetMaxCharCount(int byteCount)
{
return byteCount;
}
}

Related

Can I use class methods inside factory constructor via Dart

I have the below code that is creating the PriortyQueue structure using Dart. But since I cannot use heapify function inside the Constructor or factory constructor I cannot initialize PQ with an existing set of List. Can somebody guide me and show me how I can use heapify while creating PQ instance so I can initialize it with an existing List? Also If you have any other suggestions against doing something like this please also help me as well. thank you
class PriorityQueue<T extends Comparable<T>> {
List<T?> _tree;
PriorityQueue._(List<T?> tree) : _tree = tree;
factory PriorityQueue([List<T>? array]) {
List<T?> newArray = [null, ...array ?? []];
// ignore: todo
//TODO: missing heapify
return PriorityQueue._(newArray);
}
void insert(T node) {
_tree.add(node);
_swim(_tree.length - 1);
}
T getTop() {
_swap(1, _tree.length - 1);
T top = _tree.removeLast() as T;
_sink(1);
return top;
}
List<T> _heapify(List<T> array) {
int sinkNodeIndex = (array.length - 1) ~/ 2;
while (sinkNodeIndex >= 1) {
_sink(sinkNodeIndex);
sinkNodeIndex--;
}
}
void _sink(int nodeIndex) {
int leftChildIndex = nodeIndex * 2;
int rightChildIndex = leftChildIndex + 1;
int minNodeIndex = leftChildIndex;
// index can be unreachable
T? leftChild =
leftChildIndex >= _tree.length ? null : _tree[leftChildIndex];
T? rightChild =
rightChildIndex >= _tree.length ? null : _tree[rightChildIndex];
if (leftChild == null) {
return;
}
if (rightChild != null && leftChild.compareTo(rightChild) > 0) {
minNodeIndex = rightChildIndex;
}
if ((_tree[minNodeIndex] as T).compareTo(_tree[nodeIndex] as T) < 0) {
_swap(nodeIndex, minNodeIndex);
_sink(minNodeIndex);
}
}
void _swim(int nodeIndex) {
if (nodeIndex <= 1) return;
int parentIndex = nodeIndex ~/ 2;
if ((_tree[nodeIndex] as T).compareTo(_tree[parentIndex] as T) < 0) {
_swap(nodeIndex, parentIndex);
_swim(parentIndex);
}
}
void _swap(int i, int j) {
T temp = _tree[i] as T;
_tree[i] = _tree[j];
_tree[j] = temp;
}
#override
String toString() {
return _tree.toString();
}
}
I would make all the helper functions. _heapify, _sink/_swim, even _swap, be static functions which take the list as argument.
Then you can use them from anywhere, including inside the factory constructor.
Alternatively, you can change the constructor to returning:
return PriorityQueue._(newArray).._heapify();
This creates the PriorityQueue object, and then calls the _heapify method on it, before returning the value.
(I'd also make _tree have type List<T> and not insert the extra null at the beginning. It's more efficient to add/subtract 1 from indices than it is to cast to T.)
I ended up doing like Irn's first suggestion. But when I do functions static they lost Type of the class so I needed to specify for each function. Also, making List<T?> instead of List ended up with me fighting against the compiler.
class PriorityQueue<T extends Comparable<T>> {
List<T?> _tree;
PriorityQueue._(List<T?> tree) : _tree = tree;
factory PriorityQueue([List<T>? array]) {
List<T?> newArray = [null, ...array ?? []];
_heapify(newArray);
return PriorityQueue._(newArray);
}
bool get isNotEmpty {
return _tree.isNotEmpty;
}
void insert(T node) {
_tree.add(node);
_swim(_tree, _tree.length - 1);
}
void insertMultiple(List<T> array) {
for (var element in array) {
insert(element);
}
}
T? removeTop() {
if (_tree.length == 1) return null;
_swap(_tree, 1, _tree.length - 1);
T top = _tree.removeLast() as T;
_sink(_tree, 1);
return top;
}
void removeAll() {
_tree = [null];
}
static void _heapify<T extends Comparable<T>>(List<T?> array) {
int sinkNodeIndex = (array.length - 1) ~/ 2;
while (sinkNodeIndex >= 1) {
_sink(array, sinkNodeIndex);
sinkNodeIndex--;
}
}
static void _sink<T extends Comparable<T>>(List<T?> tree, int nodeIndex) {
int leftChildIndex = nodeIndex * 2;
int rightChildIndex = leftChildIndex + 1;
int minNodeIndex = leftChildIndex;
T? leftChild = leftChildIndex >= tree.length ? null : tree[leftChildIndex];
T? rightChild =
rightChildIndex >= tree.length ? null : tree[rightChildIndex];
if (leftChild == null) {
return;
}
if (rightChild != null && leftChild.compareTo(rightChild) > 0) {
minNodeIndex = rightChildIndex;
}
if ((tree[minNodeIndex] as T).compareTo(tree[nodeIndex] as T) < 0) {
_swap(tree, nodeIndex, minNodeIndex);
_sink(tree, minNodeIndex);
}
}
static void _swim<T extends Comparable<T>>(List<T?> tree, int nodeIndex) {
if (nodeIndex <= 1) return;
int parentIndex = nodeIndex ~/ 2;
if ((tree[nodeIndex] as T).compareTo(tree[parentIndex] as T) < 0) {
_swap(tree, nodeIndex, parentIndex);
_swim(tree, parentIndex);
}
}
static void _swap<T extends Comparable<T>>(List<T?> tree, int i, int j) {
T temp = tree[i] as T;
tree[i] = tree[j];
tree[j] = temp;
}
#override
String toString() {
return _tree.toString();
}
}

dynamic programming grid problem approach solving using BFS

We have an NxM grid, grid have one element named Bob. Bob can travel diagonally blocks only. The grid has some blocked blocks on which Bob can not travel. Write a function that returns on how many possible positions Bob can move. Solve this problem using BFS and submit the executable code in any programming language. In the following image example, Bob's positioning is at 9,3, and it can visit the places where Y is marked; hence your method should return 30.
Anybody any pseudocode or approach on how to solve this using BFS
Following solution is modified version of solution given by ( https://stackoverflow.com/users/10987431/dominicm00 ) on problem ( Using BFS to find number of possible paths for an object on a grid )
Map.java:
import java.awt.*;
public class Map {
public final int width;
public final int height;
private final Cell[][] cells;
private final Move[] moves;
private Point startPoint;
public Map(int[][] mapData) {
this.width = mapData[0].length;
this.height = mapData.length;
cells = new Cell[height][width];
// define valid movements
moves = new Move[]{
new Move(1, 1),
new Move(-1, 1),
new Move(1, -1),
new Move(-1, -1)
};
generateCells(mapData);
}
public Point getStartPoint() {
return startPoint;
}
public void setStartPoint(Point p) {
if (!isValidLocation(p)) throw new IllegalArgumentException("Invalid point");
startPoint.setLocation(p);
}
public Cell getStartCell() {
return getCellAtPoint(getStartPoint());
}
public Cell getCellAtPoint(Point p) {
if (!isValidLocation(p)) throw new IllegalArgumentException("Invalid point");
return cells[p.y][p.x];
}
private void generateCells(int[][] mapData) {
boolean foundStart = false;
for (int i = 0; i < mapData.length; i++) {
for (int j = 0; j < mapData[i].length; j++) {
/*
0 = empty space
1 = wall
2 = starting point
*/
if (mapData[i][j] == 2) {
if (foundStart) throw new IllegalArgumentException("Cannot have more than one start position");
foundStart = true;
startPoint = new Point(j, i);
} else if (mapData[i][j] != 0 && mapData[i][j] != 1) {
throw new IllegalArgumentException("Map input data must contain only 0, 1, 2");
}
cells[i][j] = new Cell(j, i, mapData[i][j] == 1);
}
}
if (!foundStart) throw new IllegalArgumentException("No start point in map data");
// Add all cells adjacencies based on up, down, left, right movement
generateAdj();
}
private void generateAdj() {
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
for (Move move : moves) {
Point p2 = new Point(j + move.getX(), i + move.getY());
if (isValidLocation(p2)) {
cells[i][j].addAdjCell(cells[p2.y][p2.x]);
}
}
}
}
}
private boolean isValidLocation(Point p) {
if (p == null) throw new IllegalArgumentException("Point cannot be null");
return (p.x >= 0 && p.y >= 0) && (p.y < cells.length && p.x < cells[p.y].length);
}
private class Move {
private int x;
private int y;
public Move(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}}
Cell.java:
import java.util.LinkedList;
public class Cell {
public final int x;
public final int y;
public final boolean isWall;
private final LinkedList<Cell> adjCells;
public Cell(int x, int y, boolean isWall) {
if (x < 0 || y < 0) throw new IllegalArgumentException("x, y must be greater than 0");
this.x = x;
this.y = y;
this.isWall = isWall;
adjCells = new LinkedList<>();
}
public void addAdjCell(Cell c) {
if (c == null) throw new IllegalArgumentException("Cell cannot be null");
adjCells.add(c);
}
public LinkedList<Cell> getAdjCells() {
return adjCells;
}}
MapHelper.java:
class MapHelper {
public static int countReachableCells(Map map) {
if (map == null) throw new IllegalArgumentException("Arguments cannot be null");
boolean[][] visited = new boolean[map.height][map.width];
// subtract one to exclude starting point
return dfs(map.getStartCell(), visited) - 1;
}
private static int dfs(Cell currentCell, boolean[][] visited) {
visited[currentCell.y][currentCell.x] = true;
int touchedCells = 0;
for (Cell adjCell : currentCell.getAdjCells()) {
if (!adjCell.isWall && !visited[adjCell.y][adjCell.x]) {
touchedCells += dfs(adjCell, visited);
}
}
return ++touchedCells;
}}
Grid.java:
public class Grid{
public static void main(String args[]){
int[][] gridData = {
{0,0,0,0,0,0,0,0},
{0,1,0,0,0,1,0,0},
{0,0,0,0,1,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,1,0,0,1,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,1,0},
{0,0,1,0,0,1,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,2,1,0,0,0}}; //2 is bobs position, 1 is blocked, 0 can be visited
Map grid = new Map(gridData);
MapHelper solution = new MapHelper();
System.out.println(solution.countReachableCells(grid));
}}
For original answer of similar problem visit (Using BFS to find number of possible paths for an object on a grid) for original answer.

Implementing stacks, ques using linked lists. Difference between "=" operator and setlink() function

This is my code
import java.util.*;
class node{
public int data;
public node link;
public node()
{
data = 0;
link = null;
}
public node(int d, node l)
{
data = d;
link = l;
}
void setlink(node n)
{
link = n;
}
void setdata(int dat)
{
data = dat;
}
int showdata()
{
return data;
}
node showlink()
{
return link;
}
}
class stack{
node top;
int size;
stack()
{
top = null;
size = 0;
}
void push()
{
node npt = new node();
size++;
System.out.println("Enter the value you want to enter :");
Scanner sc = new Scanner(System.in);
int val;
val = sc.nextInt();
npt.setdata(val);
if( top == null )
{
top = npt;
}
else
{
npt.setlink(top);
top = npt;
}
}
void pop()
{
node npt = top;
top = npt.showlink();
size--;
}
void showstack()
{
node nptr = top;
int i = 1;
while( nptr != null )
{
System.out.println("Data at position "+ i + " is : " + nptr.showdata());
i++;
nptr = nptr.showlink();
}
}
}
class stacked{
public static void main(String args[])
{
stack obj = new stack();
int temp = 0;
while( temp != 1 )
{
System.out.println("-- Enter 1 to exit -- 2 to push -- 3 to pop -- 4 to show Stack --");
Scanner sc = new Scanner(System.in);
temp = sc.nextInt();
if(temp == 1)
{
break;
}
switch(temp)
{
case 2: obj.push();
break;
case 3: obj.pop();
break;
case 4: obj.showstack();
break;
}
temp++;
}
}
}
My question is in the function void push() in class stack what is the difference between "=" operator and setlink() function.
I mean why cannot we write npt = top; instead of npt.setlink(top); ?
What does "=" do and how is the referencing done?
Thanks

Avro (Microsoft) Serialization of derived type members missing

I am evaluating the performance of Microsoft's implementation of Avro, and at first I thought I was getting phenomenal performance until I realized it just wasn't serializing the entire message ;-)
In the following there is a simple hierarchy of messages decorated with [DataContract] (a base and two derived types). All members are decorated with the [DataMember] attribute. I create a serializer from the base message type and serialize a list of derived messages, but it appears to only serialize/deserialize the base class members. All of the derived message members are missing from the result.
Am I missing something? My application will require mixed message types.
FWIW I don't see any strings from the second derived type in the binary file, so I suspect the derived type members aren't being serialized.
Thanks, Greg
class Program
{
[DataContract(Name = "SideType", Namespace = "AvroMessage")]
public enum EventType
{
Unknown = 0,
One = 1,
Two = 2
}
[DataContract(Name = "MessageBase", Namespace = "AvroMessage")]
public class MessageBase
{
[DataMember(Name = "Subtype")]
public string Subtype;
[DataMember(Name = "Timestamp")]
public DateTime Timestamp;
[DataMember(Name = "GroupName")]
public string GroupName;
public override bool Equals(object obj)
{
MessageBase other = obj as MessageBase;
if (other == null) return false;
return Subtype == other.Subtype &&
Timestamp == other.Timestamp &&
GroupName == other.GroupName;
}
}
[DataContract(Name = "SubMessage1", Namespace = "AvroMessage")]
public class SubMessage1 : MessageBase
{
[DataMember(Name = "Volume")]
public int Volume;
[DataMember(Name = "Count")]
public int Count;
[DataMember(Name = "DetectedSide")]
public EventType Event;
public override bool Equals(object obj)
{
SubMessage1 other = obj as SubMessage1;
if (other == null) return false;
return Subtype == other.Subtype &&
Timestamp == other.Timestamp &&
GroupName == other.GroupName &&
Event == other.Event &&
Volume == other.Volume &&
Count == other.Count;
}
}
[DataContract(Name = "SubMessage2", Namespace = "AvroMessage")]
public class SubMessage2 : MessageBase
{
[DataMember(Name = "Name1")]
public string Name1;
[DataMember(Name = "Volume1")]
public int Volume1;
[DataMember(Name = "Name2")]
public string Name2;
[DataMember(Name = "Volume2")]
public int Volume2;
[DataMember(Name = "PriceMove")]
public double PriceMove;
public override bool Equals(object obj)
{
SubMessage2 other = obj as SubMessage2;
if (other == null) return false;
return Subtype == other.Subtype &&
Timestamp == other.Timestamp &&
GroupName == other.GroupName &&
Volume1 == other.Volume1 &&
Name1 == other.Name1 &&
Volume2 == other.Volume2 &&
Name2 == other.Name2 &&
PriceMove == other.PriceMove;
}
}
public class MessageFactory
{
public static IEnumerable<MessageBase> CreateMessages(int number)
{
Random ran = new Random();
List<MessageBase> retval = new List<MessageBase>();
for (int i = 0; i < number; i++)
{
if (ran.Next(2) == 0)
{
SubMessage1 sub1 = new SubMessage1();
sub1.Timestamp = DateTime.Now;
sub1.GroupName = "Group" + DateTime.Now.Millisecond.ToString();
sub1.Subtype = "SubMessag1";
sub1.Volume = ran.Next(10000);
sub1.Count = ran.Next(100);
if (ran.Next(2) == 0)
{
sub1.Event = EventType.One;
}
else
{
sub1.Event = EventType.Two;
}
retval.Add(sub1);
}
else
{
SubMessage2 sub2 = new SubMessage2();
sub2.Timestamp = DateTime.Now;
sub2.GroupName = "Group" + DateTime.Now.Millisecond.ToString();
sub2.Subtype = "SubMessag2";
sub2.Volume1 = ran.Next(1000);
sub2.PriceMove = ran.NextDouble() * 100 - 50;
sub2.Volume2 = ran.Next(1000);
sub2.Name1 = "Contract" + (DateTime.Now.Millisecond + ran.Next(5)).ToString();
sub2.Name2 = "Contract" + DateTime.Now.Millisecond.ToString();
retval.Add(sub2);
}
}
return retval;
}
}
public static void TestAvro(int count)
{
bool correct = false;
long serTicks = 0;
long deserTicks = 0;
Stopwatch sw = new Stopwatch();
sw.Reset();
var serializer = Microsoft.Hadoop.Avro.AvroSerializer.Create<MessageBase>();
MessageBase[] messages = new MessageBase[count];
using (var file = File.Create(#"C:\test_avro.bin"))
{
int i = 0;
foreach (var message in MessageFactory.CreateMessages(count))
{
messages[i++] = message;
sw.Start();
serializer.Serialize(file, message);
sw.Stop();
}
}
serTicks = sw.ElapsedTicks;
sw.Reset();
List<int> badMessages = new List<int>();
using (var file = File.OpenRead(#"C:\test_avro.bin"))
{
for (int i = 0; i < count; i++)
{
sw.Start();
MessageBase message = serializer.Deserialize(file);
sw.Stop();
SubMessage1 m1 = message as SubMessage1;
SubMessage2 m2 = message as SubMessage2;
bool areNull = (m1 == null) && (m2 == null); // Always true
if (!messages[i].Equals(message)) badMessages.Add(i);
}
}
deserTicks = sw.ElapsedTicks;
correct = badMessages.Count == 0;
long size = (new FileInfo(#"C:\test_proto.bin")).Length;
Console.WriteLine(String.Format("Correct: {0}, Time Out: {1}, , Time In: {2}, , Size: {3}", correct, serTicks, deserTicks, size));
}
static void Main(string[] args)
{
TestAvro(10000);
Console.ReadLine();
}
}
My bad - I forgot the KnownType attribute on the base class, one for each derived type. It works if you include the attributes.

Sorting an array of String in BlackBerry

I need to sort an array of String like the following, in ascending order.
String str[] = {"ASE", "LSM", "BSE", "LKCSE", "DFM"};
How to do that? I need help.
This answer is based on Signare and HeartBeat's suggestion. Explore this link for details. Also this link, Sorting using java.util.Array might be helpful.
// Initialization of String array
String strs[] = {"One", "Two", "Threee", "Four", "Five", "Six", "Seven"};
// implementation of Comparator
Comparator strComparator = new Comparator() {
public int compare(Object o1, Object o2) {
return o1.toString().compareTo(o2.toString());
}
};
// Sort
Arrays.sort(strs, strComparator);
Try this -
import java.util.*;
import java.io.*;
public class TestSort1 {
String [] words = { "RĂ©al", "Real", "Raoul", "Rico" };
public static void main(String args[]) throws Exception {
try {
Writer w = getWriter();
w.write("Before :\n");
for (String s : words) {
w.write(s + " ");
}
java.util.Arrays.sort(words);
w.write("\nAfter :\n");
for (String s : words) {
w.write(s + " ");
}
w.flush();
w.close();
}
catch(Exception e){
e.printStackTrace();
}
}
// useful to output accentued characters to the console
public static Writer getWriter() throws UnsupportedEncodingException {
if (System.console() == null) {
Writer w =
new BufferedWriter
(new OutputStreamWriter(System.out, "Cp850"));
return w;
}
else {
return System.console().writer();
}
}
}
Here is my solution:-
String str[]={"ASE","LSM","BSE","LKCSE","DFM"};
for(int j = 0; j < str.length; j++){
for(int i = j + 1; i < str.length; i++) {
if(str[i].compareTo(str[j]) < 0) {
String t = str[j];
str[j] = str[i];
str[i] = t;
}
}
}

Resources