how do you reverse a string in C# using LINQ? [closed] - c#

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I was reading an old post from coding horror (http://www.codinghorror.com/blog/2007/02/why-cant-programmers-program.html) It's still a very entertaining read, you'll notice a lot of the people providing answers actually made small logical errors themselves (about 30% of them).
Anyway, thought I'll set myself a small challenge and found a bunch of fizzbuzz questions here: Alternate FizzBuzz Questions
"Reverse a String" - with all the built-in methods in the .net framework there are many ways to do this.
My question is:
1. how do you reverse a string using LINQ?
2. can you come up with other interesting ways of reversing a string in C#?
Here's are two examples I came up with
1. completely from scratch
2. using enumerable's reverse methods (1 liner)
private static string FromScratchSimplified(string input)
{
// constructed reversed char array
char[] reversedCharArray = new char[input.Length];
for (int i = 0; i < input.Length; i++)
{
reversedCharArray[i] = input[input.Length-1-i];
}
// build string from char array
string reversedString = new String(reversedCharArray);
return reversedString;
}
private static string UsingEnumerableReverseMethod(string input)
{
// using Enumerable.Reverse method
return new String(input.Reverse().ToArray());
}
Any more?

new string(Enumerable.Range(1, input.Length).Select(i => input[input.Length - i]).ToArray())

To keep it as close to query syntax as possible:
given:
string aString = "please reverse me";
then:
var reversed = new string((from c in aString.Select((value, index) => new { value, index })
orderby c.index descending
select c.value).ToArray());
Console.WriteLine(reversed);
yields:
em esrever esaelp

Related

How to insert a string in alphabetical order to a new array? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I've been looking up a lot of videos, tried using the bubble sort method, insert sort method, but nothing seems to work for this particular problem. I am supposed to add a string (movie name) to an array, but I must do it alphabetically. I can not sort the array after it's completed, it must be done while I add the new strings.
I've seen a lot posts with similar questions like this but all of them sort the array after its completed!
Here is a couple of methods that might help you.
private void PrintAlphabetically()
{
string[] movies = new string[5];
movies[0] = "b";
movies[1] = "x";
movies[2] = "m";
movies[3] = "a";
movies[4] = "t";
AddToStringArray(ref movies, "s");
Array.Sort(movies, (x, y) => String.Compare(x , y));
for (int i = 0; i < movies.Length; i++)
{
Console.WriteLine(movies[i]);
}
}
private void AddToStringArray(ref string[] array, string item)
{
List<string> list = array.OfType<string>().ToList();
list.Add(item);
array = list.ToArray();
}

Getting rid of whitespace in a dictionary [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have a dictionary
Dictionary<string, List<string>> dictGenSubs = new Dictionary<string, List<string>>();
How can I make sure that there is no whitespace in any of the records of the dictionary?
I assume you are talking only about the strings in the list.
To achieve that goal, you can use this code:
dictGenSubs = dictGenSubs.ToDictionary(
x => x.Key,
x => x.Value
.Select(x => x.Replace(" ", string.Empty))
.ToList());
This creates a new dictionary with new lists as the values of the dictionary. Each string in each list will be adjusted before being added to the new list.
A more efficient approach would be to update the existing dictionary and the existing lists:
foreach(var list in dictGenSubs.Values)
{
for(int i = 0; i < list.Count; ++i)
list[i] = list[i].Replace(" ", string.Empty);
}
Do you mean any whitespace at all in any of the strings in each value? Here's a succinctly inefficient way with LINQ:
bool hasWhitespace = dictGenSubs.SelectMany(kv => kv.Value)
.Any(s => s.Any(char.IsWhiteSpace));

Exit loop coding style [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I've got a coding style question. Below are two looping functions that do the same thing but with a slightly different loop exit technique. I just wanted to get a sense of what you guys prefer.
I personally prefer the first. I don't see why I should declare a new variable and break a loop when I know there's nothing else to be done.
private SomeObj getSomeObj(ArrayList<SomeObj> items, String type)
{
for (SomeObj someObj : items) {
if ( someObj.getField().equals(type) ) {
return someObj;
}
}
return null;
}
private SomeObj getSomeObj(ArrayList<SomeObj> items, String type)
{
SomeObj found = null
for (SomeObj someObj : items) {
if ( someObj.getField().equals(type) ) {
found = someObj;
break;
}
}
return found;
}
Both have different purposes. They are not replacements for each other.
First one comes out from the method
Second one comes out from the loop NOT method.
Let us say if there is some code which manipulates SomeObj after the for loop, then results will differ from first method to second method.
I prefer the first. In general, i prefer early exits from methods as it tends to reduce nesting.
Both approaches could not replace each other in every situation. Suppose you want to execute the code after loop finishes then return could not do that for you and vice versa. In your case both could be used but not in every situation.
Statements after for loop, which you do not want to execute get executed with break
private SomeObj getSomeObj(ArrayList<SomeObj> items, String type)
{
SomeObj found = null
for (SomeObj someObj : items) {
if ( someObj.getField().equals(type) ) {
found = someObj;
break;
}
}
//Statements you do not want to execute get executed with break
return found;
}
Statements after for loop, which you want to execute do not get executed with return
private SomeObj getSomeObj(ArrayList<SomeObj> items, String type)
{
SomeObj found = null
for (SomeObj someObj : items) {
if ( someObj.getField().equals(type) ) {
found = someObj;
return;
}
}
//Statements you want to execute do not get executed with return
return found;
}

c# string tricks/features? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have always hated string parsing, something I am doing a lot of in a current project.
Does c# have and tricks or quick features for strings that would make my life easier? In particular cropping, multiplying or substringing? The end goal here is to take a list of string and turn it into a nice pretty columned structure. Easy, but still, I would it to be python easy.
For example, python has:
>>> a = "I once was a string, then I got mutilated"
>>> print a[20:]
then I got mutilated
or
>>> 'chicken' in 'chicken noodle soup'
True
or finally
>>> 'lol' * 5
'lollollollollol'
There aren't language related features for this in C# like there are in Python. The only real C# language feature with strings is allowing + to be mapped to String.Concat, to simplify (and keep efficient) "a" + "b" + "c" statements.
The String class provides this functionality via methods, however. There is also StringBuilder, which is used for building large strings based on multiple concatenations.
In your example, see String.Substring for slicing and String.Contains for in. There isn't a simple "repeat" style operation like the multiplication in Python.
That being said, it's easy to make an extension method which handles the multiply functionality.
They're different languages - the syntax is different and comparing C# to Python in this way is largely pointless. Also I completely challenge your assertion that the examples you've given are 'easier'.
I don't see how you can get much easier than:
Console.WriteLine("Foo".Substring(1)); //<-- prints 'oo'
Console.WriteLine("chicken noodle soup".Contains("chicken")
.ToString()); //<-- prints 'true'
And for the last one, read this SO: Can I "multiply" a string (in C#)?
Personally, in particular, I hate the idea of multiplying a string - too much ambiguity if that value happens to be '5' - hiding such functionality behind operators smells.
First Question
You can use String.SubString():
string a = "I once was a string, then I got mutilated";
string lastTwentyCharactersOfA = a.Substring(Math.Max(0, a.Length - 20));
// returns "then I got mutilated"
Credit where credit is due: This answer does a nice job of making sure that you don't get an exception if your string has less characters than you are requesting.
Second Question
You can use String.Contains():
string soup = "chicken noodle soup";
bool soupContainsChicken = soup.Contains("chicken"); // returns True
Third Question
You can't override the multiplication operator for the String class. It's a sealed class, and of course you don't have access to the source code to make it a partial class or something along those lines. You have a couple of options that will get you close to what you want to do. One is to write an extension method:
public static string MultiplyBy(this string s, int times)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < times; i++)
{
sb.Append(s);
}
return sb.ToString();
}
Usage:
string lol = "lol";
string trololol = lol.MultiplyBy(5); // returns "lollollollollol"
Or if you want to go the route of operator overloading, you can write a custom String class of sorts and then have at it.
public struct BetterString // probably not better than System.String at all
{
public string Value { get; set; }
public static BetterString operator *(BetterString s, int times)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < times; i++)
{
sb.Append(s.Value);
}
return new BetterString { Value = sb.ToString() };
}
}
Usage:
BetterString lol = new BetterString { Value = "lol" };
BetterString trololol = lol * 5; // trololol.Value is "lollollollollol"
In general, there's a lot you can do with System.String and System.Text.StringBuilder. And the possibilities are almost endless with extension methods. Check out MSDN if you are interested in learning the ins and outs of it all.
using linq, you can treat your string like a list of chars and do what you want easy enough.
var chickenString = "chicken noodle soup";
var hasChicken = chickenString.Contains("chicken");
// hasChicken = true at this point...

What different ways can you write this [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
There are some cool and exciting features in .NET 3.5/C# 3.0, and with those features comes some darn interesting ways to write the exact same line of code.
Using the above stated tool set (and by extension .NET 2.0 stuff), what are the different ways the below code snippet could reasonably be rewritten?
string uploadDirectory = "c:\\some\\path\\";
if (Directory.Exists(uploadDirectory)) {
string[] files = Directory.GetFiles(uploadDirectory);
foreach (string filename in files) {
if (File.GetLastWriteTime(filename).AddHours(12) < DateTime.Now) {
File.Delete(filename);
}
}
}
Lambda:
if (Directory.Exists(uploadDirectory))
Directory.GetFiles(uploadDirectory)
.Where(f => File.GetLastWriteTime(file) < DateTime.Now.AddHours(-12))
.Each(f => File.Delete(f));
Edit: On 2nd thought, you can avoid the security lookups on each File access by using DirectoryInfo and FileInfo instead of the static File methods:
var di = new DirectoryInfo(uploadDirectory);
if (di.Exists()) {
di.GetFiles()
.Where(f => f.LastWriteTime < DateTime.Now.AddHours(-12))
.Each(f=> f.Delete());
}
And for those missing their own Each method:
void Each<T>(this IEnumerable e, Action<T> action) {
foreach (T t in e) {
action(t);
}
}
To make this really crazy, and fit the C# 3.0 theme, let's throw in an anonymous type:
di.GetFiles().Select(f => new() {
Delete = f.LastWriteTime < DateTime.Now.AddHours(-12) ? f.Delete : () => { }
}).Delete();
But that just doesn't make any sense. ;)
Well, the first bit maps quite neatly to a LINQ query... but there is (deliberately) no ForEach in regular LINQ. We can annoy Eric and add one, though ;-p
So the following uses LINQ and a custom extension method - but we could re-write the exact same code (i.e. the same IL) as:
query syntax (as below)
fluent syntax (.Where().Select() ec)
explicit static (Enumerable.Where(...))
lambdas vs anonymous methods vs named methods (last changes the IL)
delegates with/without the abbreviated (C# 2.0) delegate "new" syntax
generic calls with/without generic type inference (Where() vs Where<T>())
call to File.Delete vs call to x=>File.Delete(x) etc
etc
static void Main()
{
string uploadDirectory = "c:\\some\\path\\";
if (Directory.Exists(uploadDirectory))
{
var files = from filename in Directory.GetFiles(uploadDirectory)
where File.GetLastWriteTime(filename) < DateTime.Now.AddHours(-12)
select filename;
files.ForEach(File.Delete);
}
}
static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
{
foreach (T item in items)
{
action(item);
}
}
We could write the DateTime code with a custom Expression, but that would be overkill...
However, I doubt we could ever run out of ways of writing it ;-p

Categories

Resources