I am new in c#.So please help.
The first line of input has a unique integer N that indicates the number of sets of strings, each set may contain between 1 and 50 inclusive elements, and each of the strings of the set may contain between 1 and 50 inclusive characters.
How i take input from user above this condition??
example:
enter integer number:3
My dream is big
I want to go school
You are so sweet
Here's what you need to do.
Split the string into array.
Sort the array using an IComparer that compares the length of each string in the array
Join the string array into a single string
See this function below:
public static string SortStringByLength(string input, Order order) {
string[] words = input.Split(' ');
if (order == Order.ASC)
Array.Sort(words, (x, y) => x.Length.CompareTo(y.Length));
else
Array.Sort(words, (x, y) => y.Length.CompareTo(x.Length));
return string.Join(" ", words);
}
And here's a demo to see it in action.
Related
I am writing program to add numbers from string which will be seperated from delimeters
private static readonly char[] Separators = { ',', '\n', '/','#' };
public int Add(string numbers)
{
if (numbers.Equals(string.Empty))
{
return 0;
}
return numbers.Split(Separators).Select(int.Parse).Sum();
}
When i pass the following string to Add method //#\n2#3
Then i get below error Input string was not in a correct format.
I expect answer to be 5
By default, string.Split will create empty groups if two delimiters are right next to each other. For example "3,,4".Split(','); will produce an array with three elements ("3", empty string, and "4").
You can change this in one of two ways. The first (and probably simpler) is to have the Split ignore empty entries.
numbers.Split(Separators, StringSplitOptions.RemoveEmptyEntries)
Or you can use Where in Linq
numbers.Split(Separators).Where(x => x.Length > 0)
This will prevent elements with a blank string value reaching int.Parse. Of course, there are still other things you should do to validate your input before attempting to parse, but that's another topic.
This is a question around how the compiler/language deals with this.
Take the following code:
Console.WriteLine("Enter some numbers separated by ",");
var numbers = Console.ReadLine();
var splitNumber = numbers.Split(',');
var maxNumber = splitNumber.Max();
Console.WriteLine("highest is: " + maxNumber);
Entering a string such as "1,2,3,4,5" will output the 5 as the max number.
However, using "1,2,3,55,6" outputs 6. Whereas, "33,1,4,1" gives 4. Bizarrely, "33,1,2,3" gives 33.
I know there is a better/simpler/different way of doing this using a loop. I am totally missing something with how the compiler is treating these strings to determine the output. Can someone explain it? Or provide me a reference to look it up?
In string comparison, 6 > 55 returns True.
Do this instead, Split the string into an array using Split() Extension method and then use MAX() function which Returns the maximum value in a generic sequence available in LINQ
string x = "1,2,3,55,6";
var array = x.Split(',');
Console.WriteLine("highest is: " + array.Max(c => int.Parse(c)));
Output:
highest is: 55
The "max" string is the last string in lexicographical order, i.e. the order you would list them in a dictionary
You need to use e.g. int.Parse to convert your strings to a number type if you want the numeric maximum.
You need to compare the number as ints from a list or array.
var <int> Numbers = new List<int>();
while(String had not ended)
{
var splitNumber = (int) numbers.Split(',');
Numbers.Add(splitNumner);
}
var maxNumber = Numbers.Max();
Console.WriteLine("highest is: " + maxNumber);
You can do this, Convert the string array to an array of int using ConvertAll and then find the max
Console.WriteLine("Enter some numbers separated by ");
var numbers = Console.ReadLine();
var splitNumber = numbers.Split(',');
int[] myInts = Array.ConvertAll(splitNumber, int.Parse);
var maxNumber = myInts.Max();
Console.WriteLine("highest is: " + maxNumber);
I tried compiling your code with same inputs. I have also getting the same output but i thing when u try to perform .Max() operation on a string array it is only comparing the first character of each entries in your second array.
If the input is 1,2,3,55,6 you are gonna get the output as 6 because when you compare all the numbers and there first digit 6 is the largest. But if you change the input to 1,2,3,75,6 now you are gonna get the output as 75 because 7 is the biggest first digit of all the numbers in the list.
string str = "1,2,3,75,6";
var splitNumber = str.Split(',');
var maxNumber = splitNumber.Max();
Like all the other answers u need to convert the string array into an integer array and then apply it.
Ans for how the compiler is treating these strings to determine the output?:
As these are strings, string equality gets checked for it.
The compiler takes each string value and compares it to one by one char. It deduces equality on the first occurrence of mismatch (e.g. in 55 vs 6, 5 is less than 6, hence 55 is less than 6)
You can use this :
Console.WriteLine("Enter a series of number separated by comma and I will tell you which one is the biggest, cool!");
var input = Console.ReadLine().Split(',');
Console.WriteLine("Biggest is :" + input.Max(c => int.Parse(c)));
You can also do this:
var splitNumber = numbers.Split(',').Select(c=>Convert.ToInt32(c)).Max();
Console.WriteLine("highest is: " + splitNumber);
change Var to Int64
Int64 maxNumber = Int64.Parse(splitNumber.Max());
Below is my string array :
string[] arr = {
"region1.mp3,region1-sub.mp3,region1-sub1.mp3,region2-sub.mp3",
"region2.mp3,region2-Sub1.mp3",
"region3.mp3"
};
Below is my value which I am trying to search in above string array and get index:
string searchItem = "region1-sub1.mp3";
This is how I am trying to search but getting -1 (-1 indicates search not found I guess):
int index = Array.FindIndex(arr, t => t == searchItem); // -1
I understand that because my records in string array are comma separated that is why this search is failing.
So any other method which can help me find index without looping and generating new string array?
Expected Output : 0
You want to split every string by comma:
int index = Array.FindIndex(arr, t => t.Split(',').Contains(searchItem));
This works even if the string doesn't contain a comma.
This will you give you your desired output.
int index = Array.FindIndex(arr, t => t.Contains(searchItem));
int index = Array.FindIndex(arr, t => t.Contains(searchItem));
This returns 0.
This question already has answers here:
Alphanumeric sorting using LINQ
(12 answers)
Closed 6 years ago.
I have a list containing data with string and number. I have to order it in ascending and descending order.
id data
------------------
1 data1#%
2 data10
3 data
4 #$data
5 data2
I fetch the record and store it in list "List". Then I order it in ascending, but "data10" is coming in b/w "data1" and "data2". Below is my code
var o/p = List.OrderBy(x => x.data);
expected output - data1, data2 and data10
You are currently sorting it based on the string values, which will sort it by dictionary value. In a dictionary, "10" will appear between "1" and "2" because that is alphabetical order - it does not recognize that it is sorting numbers.
True alphanumeric sorting can get pretty complex, but based on your data you might be able to simplify it. Assuming your string "data1", "data2", and "data10" is a consistent pattern, you can do something like this:
var op = List.OrderBy(x => int.Parse(x.data.substring(4)));
Alternatively, if the value before the number isn't a constant length, you can use Regex to pull the number value out:
var op = List.OrderBy(x => int.Parse(Regex.Match(x.data, "\\d+").Value));
To get what you want, you need to pad the numeric portion in your order by clause, something like:
var o/p = List.OrderBy(x => PadNumbers(x.Data));
where PadNumbers could be defined as StackOverflow user Nathan has written here:
public static string PadNumbers(string input)
{
return Regex.Replace(input, "[0-9]+", match => match.Value.PadLeft(10, '0'));
}
This pads zeros for any number (or numbers) that appear in the input string so that OrderBy sees:
data0000000001
data0000000010
data0000000002
The padding only happens on the key used for comparison. The original strings (without padding) are preserved in the result.
Note : This approach assumes a maximum number of digits for numbers in the input.
I have a string consist of integer numbers followed by "|" followed by some binary data.
Example.
321654|<some binary data here>
How do i get the numbers in front of the string in the lowest resource usage possible?
i did get the index of the symbol,
string s = "321654654|llasdkjjkwerklsdmv"
int d = s.IndexOf("|");
string n = s.Substring(d + 1).Trim();//did try other trim but unsuccessful
What to do next? Tried copyto but copyto only support char[].
Assuming you only want the numbers before the pipe, you can do:
string n = s.Substring(0, d);
(Make it d + 1 if you want the pipe character to also be included.)
I might be wrong, but I think you are under the impression that the parameter to string.Substring(int) represents "length." It does not; it represents the "start-index" of the desired substring, taken up to the end of the string.
s.Substring(0,d);
You can use String.Split() here is a reference http://msdn.microsoft.com/en-us/library/ms228388%28VS.80%29.aspx
string n = (s.Split("|"))[0] //this gets you the numbers
string o = (s.Split("|"))[1] //this gets you the letters