C# Sorting element inside an array - c#

I'm trying to do a sorting for my result.
Eg: result = 04,07,01,57,83,39 Expect: result = 01,04,07,39,57,83
I have been try use array.sort, but the result will be return like ,,,,,00013345778
So is there any solution to get my expect result?
This is the code I try to do:
String result = 04,07,01,57,83,39;
Sorting(result);
public static string Sorting(string input)
{
char[] characters = input.ToArray();
Array.Sort(characters);
return new string(characters);
}

It is ambiguous whether the original data is a string or an integer.
If it's an integer, #Carlos Jafet Neto's answer would be appropriate.
If it is a character string, it will be as follows.
static void Main(string[] args)
{
String result = "04,07,01,57,83,39";
Console.WriteLine(Sorting(result));
}
public static string Sorting(string input)
{
string[] characters = input.Split(',');
Array.Sort(characters);
return string.Join(',',characters);
}

You can do something like this:
public static void Main()
{
int[] arr = new int[] {04,07,01,57,83,39};
Array.Sort(arr);
foreach(int value in arr)
{
Console.Write(value + " ");
}
}
I notice two things you are missing in your code: the brackets in the array declaration as string[ ] or int[ ], and to declare an array literal, the syntax is like this:
string[] values = {"one", "two", "three", "four"};

First of all, there is a compilation error in your code (string literal should be enclosed in "" like "this is c# string")
Second of all, when you perform ToArray() on your string you get back an array of characters which is the following for this string "01, 02, 03": ['0', '1', ',', ' ', '0', '2', ',', ' ', '0', '3'].
So to sort this string as an array of integers you first should convert it to an array of integers like this:
int[] sorted = str.Split(',')
.Select(s => int.Parse(s.Trim()))
.OrderBy(val => val)
.ToArray();
Or as correctly noticed #kunif in his answer you may sort array of strings after Split (without parsing in to int) if you need get back a string rather than an integers array. Notice however that if in your string there are values with different length like 153 and 16, this may lead to incorrect results, because strings are sorted character by character and since '5' is less than '6', "153" is less than "16". I guess you added leading zeros to your values to prevent this problem from happening. So the right answer actually depends on your needs.

Related

Why do i get this error, 'Input string was not in a correct format.'

I am trying to get an input of #1-1-1 and I need to take the numbers from this string and put them into a list of type int. I have tried to do this using this code:
List<int>numbers = new List<int>();
numbers = Console.ReadLine().Split('-', '#').ToList().ConvertAll<int>(Convert.ToInt32);
Shouldn't the input get split into an array of the numbers I want, then get turned into a list, then get converted into a int list?
Your problem is not the .split('-','#'). This splits the string into a string[] with four entrys (in this example). The first one is an empty string. This cannot be convertet into a Int32.
As a hotfix:
var numbers = Console.ReadLine().Split('-', '#').ToList();
//numbers.RemoveAt(0); <- this is also working
numbers.Remove(string.Empty);
var ret = numbers.ConvertAll<int>(Convert.ToInt32);
That will work for your "#1-1-1 " case. But you should check for non integer chars in the list before converting.
string input = " #1-1-1";
var numbers = Console.ReadLine().Replace("#", "").Split('-').Select(int.Parse).ToList();
You can do it this way
List<int> numbers = new List<int>();
string[] separators = new string[] { "-", "#" };
numbers = Console.ReadLine().Split(separators,StringSplitOptions.RemoveEmptyEntries).ToList().ConvertAll<int>(Convert.ToInt32);

retrieving data from array

I have byte[] array Q that contains some data.To convert the array to string I'm using result=System.Text.Encoding.ASCII.GetString(Q); The result is something like JOBID: 196035002\n .I need only the integer part of it. Is there a way to get only the int value 196035002 without converting to string and splitting into another array?
I think the language you are talking about is C#. What you need to do is:
char[] delimiterChars = { ':' };
string[] words = result.Split(delimiterChars);
foreach (string s in words)
{
System.Console.WriteLine(s);
}
If you don't want to use functions like Split then you can try this regex to get the desired output.
String inputString = "JOBID: 196035002\n";
Int32 result = Convert.ToInt32(Regex.Match(inputString, #"\d+").Value);
NameSpace for Regex: using System.Text.RegularExpressions;

How to split a string at each character

I am using ASP.NET Web Pages to create a project in which I am assigned to place each character of the user's (customer's) name in each seperate input block.
For that I am getting the value from the Sql Server CE Database and then I am trying to convert it into an array of one character for each input. I have tried the following code for that
var form_data = db.QuerySingle("SELECT * FROM Form_Data WHERE Form_Id =#0", form_id);
var name_emp = form_data.Name_Emig;
if(name_emp != null) {
name_emp = name_emp.ToString().Split('');
}
It generates the following Compiler error:
http://msdn.microsoft.com/en-us/library/8eb78ww7(v=vs.90).aspx (Compiler error: CS1011)
Which means that the character cannot be initialized by an empty value. I want to convert that value in one character each array.
The name is as: Afzaal Ahmad Zeeshan. So, in each input it would be placed inside the value of it. But the code I am using isn't working. Any suggestion to split the string at each character, so the result would be
{'A', 'F', 'Z', 'A', 'A', 'L' ...}
It doesn't matter whether result is Capital case or lower case. I will convert it to the desired one later.
You can try using ToCharArray().
So your code would be this:
var form_data = db.QuerySingle("SELECT * FROM Form_Data WHERE Form_Id =#0", form_id);
var name_emp = form_data.Name_Emig;
if(name_emp != null) {
name_emp = name_emp.ToCharArray();
}
You can use this to iterate with each item :
string yourString = "test";
foreach(var character in yourString)
{
// do something with each character.
}
Or this to get all characters in a char[]
char[] characters = yourstring.ToCharArray();
Try name_emp.ToArray(). A string implements IEnumerable<char>, so ToArray will return an array of the char.
Edit:
Actually I suppose ToCharArray is better in this case...

string.Split ignores Null values between delimiters

I'm trying to convert some data into sql statements with the use of Streamreader and Streamwriter.
My problem is, when i split lines which in which between 2 delimiters is nothing, not even a space, they get ignored and i get a IndexOutOfRange error
because my temparray only goes till temparray[3] , but it should go to like temparray[6] ..
How can i split and use Null values or replace those null values with a simple char, so that i dont get an IndexOutOfRange error when i want to create my sql statements ?
foreach (string a in values)
{
int temp = 1;
String[] temparray = a.Split(';');
streamWriter.WriteLine("Insert into table Firma values({0},'{1}','{2}')", temp, temparray[1], temparray[4]);
temp++;
}
First of all, this is asking for trouble (SQL injection). You should at the very least escape the values parsed from the string.
And you seem to be mistaken, as String.Split does exactly what you want by default: "x;y;;z".Split(';') returns a four-element array {"x", "y", "", "z"}. You can achieve the described behavior by using StringSplitOptions.RemoveEmptyEntries: "x;y;;z".Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries) returns a three-element array {"x", "y", "z"}. Which is what you do not want, as you say.
Either way, "Überarbeitung der SAV Seite;b.i.b.;;;;PB;".Split(';') returns a seven-element array here for me, so check your inputs and implementation…
If you print out your string, I'm pretty sure it will not be what you expect it to be.
static void Main(string[] args)
{
var result = "Überarbeitung der SAV Seite;b.i.b.;;;;PB;".Split(';');
foreach (var part in result)
{
Console.WriteLine(" --> " + part);
}
Console.ReadLine();
}
This works great. It will not ignore the empty values. It will print
--> Überarbeitung der SAV Seite
--> b.i.b.
-->
-->
-->
--> PB
-->
including the empty values.
Greetings to bib Paderborn :)
If you're using SQL Server, you can return empty strings instead of null by using the ISNULL operator in your query.
For example:
SELECT ISNULL(PR_Arbeitstitel, '') FROM Table
Why don't you iterate over your temparray to build up a string of param values.
This is by no means perfect, but should point you in the direction
foreach (string a in values)
{
int temp = 1;
String[] temparray = a.Split(';');
var stringBuilder = new StringBuilder();
foreach (var s in temparray)
stringBuilder.Append("'" + s + "',");
var insertStatement = string.Format("Insert into table Firma values({0}, {1})", temp, stringBuilder.ToString().TrimEnd(','));
temp++;
}
Why would you have 2 delimiters in a row with nothing inbetween them? Do you not control the input?
In that case you could control it by inserting a so-called sentinel value, such as "IGNOREMEPLEASE":
String[] temparray = a.Replace(";;", ";IGNOREMEPLEASE;").Split(';');
Then the rest of your code knows that IGNOREMEPLEASE means there was an empty line, and it should be ignored.
That being said, be very careful about what you send to a database, and scrub incoming data that you use to build SQL statements with, to get rid of anything dangerous.
I don't see your issue occurring. The following outputs a string.Empty for string[2] and has all 5 elements
string[] str = "0,1,,3,4".Split(new char[] { ',' });
foreach (string s in str)
{
Debug.Print(s);
}
output
0
1
3
4
I've tried to reproduce with your example of string "Überarbeitung der SAV Seite;b.i.b.;;;;PB;" but everything was fine. I've got 7 items in array.
You can try to use
string s = "Überarbeitung der SAV Seite;b.i.b.;;;;PB;";
var result = s.Split(new[] { ';' }, StringSplitOptions.None);
To be sure that StringSplitOptions.RemoveEmptyEntries is not enabled.
Perhaps use the ?? operator:
streamWriter.WriteLine(
"Insert into table Firma values({0},'{1}','{2}')",
temp,
temparray[1] ?? 'x',
temparray[4] ?? 'x');
This still is only safe, though, if you know for sure that your input has at least 5 tokens after splitting. If you can't guarantee this you'll need to wrap it in a conditional:
if (temparray.Length < 5)
{
// handle invalid input
}

Substring values into multiple textboxes

I want to seperate multiple values from a gridview control and show it in four textboxes. Is that possible?
Right now I get this value:
With this code:
var lblRef = new Label
{
Text = ((Label) row.FindControl("LabelAssignmentReference")).Text
};
string valueTextBox = lblRef.Text;
int indexOfRefSwe = valueTextBox.IndexOf(",", StringComparison.Ordinal);
string valueRef = valueTextBox.Substring(0, indexOfRefSwe);
TextBoxReference.Text = valueRef;
But how do i get it in multiple values? ` TextBoxReference.Text = valueRef;
TextBoxRefPhone.Text = "??";
TextBoxRefEmail.Text = "??";
TextBoxRefDesc.Text = "??";`
This should get you started.
string[] splits = lblRef.Text.Split(',');
Console.WriteLine(splits[0]); // refname
Console.WriteLine(splits[1]); // 08712332
Console.WriteLine(splits[2]); // ref#gmail.com
Console.WriteLine(splits[3]); // refdescription
I suggest also adding validation checks to make sure you don't get any errors, such as checking that splits.Length == 4 as expected.
Note that the spaces will be included in the beginning of the last three elements of splits. You can eliminate those using the Trim method, or by providing an array of delimiters new[] {',', ' '} to the split function and ignore empty elements (there's an overload for that).
There is System.String.Split()-method:
string[] parts = str.Split(new char[] {','});
Afterwards, work on the parts.
Example from MSDN
using System;
public class SplitTest {
public static void Main() {
string words = "This is a list of words, with: a bit of punctuation" +
"\tand a tab character.";
string [] split = words.Split(new Char [] {' ', ',', '.', ':', '\t' });
foreach (string s in split) {
if (s.Trim() != "")
Console.WriteLine(s);
}
}
}
you can do as below
var values = lblRef.Text.Split(',');
TextBoxRefPhone.Text = values[0];
if(values.Length>0)
TextBoxRefEmail.Text =values[1];
if(values.Length>1)
TextBoxRefDesc.Text = values[2];
Edit
there is a Split overload method which accept params. so we can give one character
public string[] Split(params char[] separator);
The params keyword lets you specify a method parameter that takes an
argument where the number of arguments is variable.

Categories

Resources