Reverse the letter case in a string using List - c#

I don't understand where is my mistake, and would appreciate help. I would like to reverse the letter case in a string and return reversed chars to the List using List.Add() method.
using System.Linq;
using System.Collections.Generic;
using System;
public class Program
{
public static string ReverseCase(string str)
{
List<char> result = new List<char>();
foreach(char pew in str){
char.IsUpper(pew) ? result.Add(Char.ToLower(pew)):result.Add(Char.ToUpper(pew));
}
return result.ToString();
}
}

There are two issues here - first, the usage of the ? operator - you can't use code blocks there, just values. So instead of using it with two Add calls, you can use it to get the correct value within an Add call.
Second, calling ToString() on a List won't do what you expect it to do. You could, however, join the characters in the list to get a string:
public static string ReverseCase(string str)
{
List<char> result = new List<char>();
foreach(char pew in str){
result.Add(char.IsUpper(pew) ? Char.ToLower(pew) : Char.ToUpper(pew));
}
return String.Join("", result);
}

Get the char first and add it to the list, like this approach :
public static string ReverseCase(string str)
{
List<char> result = new List<char>();
foreach (char pew in str)
{
result.Add(char.IsUpper(pew) ? char.ToLower(pew) : char.ToUpper(pew));
}
return new string(result.ToArray());
}
Note that, result.ToString() can't convert list of char to string.
I hope you find this helpful.

Related

Console.Writeline escape character from variable

I've got an extension method that converts me ulong into a string value with some kind of encryption. I want to output them as they are just by using Console.WriteLine, in most scenarios it works but there is a problem with values with escapes characters. For example "(V\\\|RN" outputs just "(V\|RN".
var result = id.IdToCode();
Console.WriteLine(result);
or
Console.WriteLine(id.IdToCode());
The method IdToCode returns stringBuilder.ToString()
I've tried many combinations with putting somewhere # to return the string as it is but without any result. Maybe I should override the default behavior of Console.WriteLine or the stringBuilder.ToString() is the problem here?
Here is a screen of what I mean.
And below the code of IdToCode method:
public static string IdToCode(this ulong value)
{
const string charArray = #"1234890qwertyuiopbnmQWERTYUasdfghjklzxcvIOPASDFGHJKLZXCVBNM!+={}[]|\<>?##567$%^&*()-_";
StringBuilder stringBuilder = new StringBuilder();
ulong num = value;
while (num != 0UL)
{
ulong index = num % (ulong)charArray.Length;
num /= (ulong)charArray.Length;
stringBuilder.Insert(0, charArray[(int)index].ToString());
}
return stringBuilder.ToString();
}
I've changed the char array into different one but the general method it's the same as above.
The problem is you need to use the # in front of the string literal which actually adds the backslash to the StringBuilder.
There is no point in doing #id.IdToCode(), because when the string is returned, it already contains (V\|RN. The tooltip shows \\ because it shows the escaped eversion - meaning the single backslash.
One thing that is certain is that the problem can't be resolved here, but only inside the IdToCode method, where it actually originates.
Compare this (same as your code):
static void Main(string[] args)
{
var str = IdToCode();
Console.WriteLine();
}
public static string IdToCode()
{
return "(\\VN";
}
Hovering over str I see (\\VN - two backslashes, output is just one backslash - which is correct.
And this:
static void Main(string[] args)
{
var str = IdToCode();
Console.WriteLine();
}
public static string IdToCode()
{
return #"(\\VN";
}
Here the tooltip shows "(\\\\VN" which is again correct - there are two actual backslashes and console output is the desired (\\VN

Cypher Program on C# with a function

Why doesn't my code work?? I am writing a cypher program in C# and would like to know why this isn't working. The error that I keep on getting is 'not all code paths return a value'
this is my code:
If passed string will be empty then the return will never be hit, so the method will not return anything.
public static string cypher(string word)
{
// If word is null, we just return null.
if(string.IsNullOrEmpty(word))
return null;
// Process string. This will return after first char...
foreach (char d in word)
{
char charCypher = System.Convert.ToChar((int)d+2);
return Convert.ToString(charCypher);
}
}
Not exactly what the question is about, but you iterate through each char of a word, but you return after first char. You probably want to cypher every char and return cyphered word. In this case you need to modify your code:
public static string cypher(string word)
{
// If word is null, we just return null.
if(string.IsNullOrEmpty(word))
return null;
StringBuilder builder = new StringBuilder();
foreach (char d in word)
{
char charCypher = System.Convert.ToChar((int)d+2);
builder.Append(Convert.ToString(charCypher));
}
return builder.ToString();
}
The foreach loop in cypher can contain an empty string, so the loop won't be executed if that's the case. Therefore it won't hit your return statement.
A workaround for this problem could be adding return String.Empty before the last closing brace or your method.
It seems, that you want to implement Caesar cipher:
using System.Linq;
...
public static string cypher(string word) {
//DONE: do not forget to validate public method's arguments
if (string.IsNullOrEmpty(word))
return word;
//TODO: you may want to make some amendments
// 1. Filter out which characters to encode (e.g. skip new lines)
// 2. Add modulo operator (e.g. to encode letters as letters)
return string.Concat(word.Select(d => (char)(d + 2)));
}
Please, do not forget to cast integer back to char when concatenating the string

c# if contains AND/OR

Is there a variant of this?
if (blabla.Contains("I'm a noob") | blabla.Contains("sry") | blabla.Contains("I'm a noob "+"sry"))
{
//stuff
}
like:
if (blabla.Contains("I'm a noob) and/or ("sry")
{
//stuff
}
Help is appreciated!
You can't collapse it quite as far as you asked, but you can do:
if (blabla.Contains("I'm a noob") || blabla.Contains("sry"))
{
//stuff
}
The "and" case is handled here because a string with both would actually pass both of the statements in the "Or".
As far as I'm aware, there are no built-in methods to do this. But with a little LINQ and extension methods, you can create your own methods that will check to see if a string contains any or all tokens:
public static class ExtensionMethods{
public static bool ContainsAny(this string s, params string[] tokens){
return tokens.Any(t => s.Contains(t));
}
public static bool ContainsAll(this string s, params string[] tokens){
return tokens.All(t => s.Contains(t));
}
}
You could use it like this (remember, params arrays take a variable number of parameters, so you're not limited to just two like in my example):
var str = "this is a string";
Console.WriteLine(str.ContainsAny("this", "fake"));
Console.WriteLine(str.ContainsAny("doesn't", "exist"));
Console.WriteLine(str.ContainsAll("this", "is"));
Console.WriteLine(str.ContainsAll("this", "fake"));
Output:
True
False
True
False
Edit:
For the record, LINQ is not necessary. You could just as easily write them this way:
public static class ExtensionMethods{
public static bool ContainsAny(this string s, params string[] tokens){
foreach(string token in tokens)
if(s.Contains(token)) return true;
return false;
}
public static bool ContainsAll(this string s, params string[] tokens){
foreach(string token in tokens)
if(!s.Contains(token)) return false;
return true;
}
}
var arr = new[]{"I'm a noob" ,"sry", "I'm a noob +sry"};
if(arr.Any(x => blabla.Contains(x)))
{
}
You can use a regex:
Regex r = new Regex("I'm a noob|sry|I'm a noob sry");
if(r.IsMatch(blabla)) {
//TODO: do something
}
Regular expressions have other advanced features like: a* matches with the empty string, a, aa, aaa,...
The funny part is that if you "compile" the regex (for instance using new Regex("I'm a noob|sry|I'm a noob sry",RegexOptions.Compiled), C# will turn it automatically into the fastest solution mechanism possible. For instance if blabla is a 100k chars string, you will only run once over the entire string. And for instance redundant parts like I'm a noob sry will be omitted automatically.

How to lowercase a string except for first character with C#

How do convert a string to lowercase except for the first character?
Can this be completed with LINQ?
Thanks
If you only have one word in the string, you can use TextInfo.ToTitleCase. No need to use Linq.
As #Guffa noted:
This will convert any string to title case, so, "hello world" and "HELLO WORLD" would both be converted to "Hello World".
To achieve exectly what you asked (convert all characters to lower, except the first one), you can do the following:
string mostLower = myString.Substring(0, 1) + myString.Substring(1).ToLower();
This can be done with simple string operations:
s = s.Substring(0, 1) + s.Substring(1).ToLower();
Note that this does exactly what you asked for, i.e. it converts all characters to lower case except the first one that is left unchanged.
If you instead also want to change the first character to upper case, you would do:
s = s.Substring(0, 1).ToUpper() + s.Substring(1).ToLower();
Note that this code assumes that there is at least two characters in the strings. If there is a possibility that it's shorter, you should of course test for that first.
String newString = new String(str.Select((ch, index) => (index == 0) ? ch : Char.ToLower(ch)).ToArray());
Use namespace: using System.Globalization;
...
string value = CultureInfo.CurrentCulture.TextInfo.ToTitleCase("hello");
EDIT
This code work only if its single word .For convert all character into lower except first letter check Guffa Answer.
string value = myString.Substring(0, 1) + myString.Substring(1).ToLower();
Not sure you can do it in linq here is a non-linq approach:
public static string FirstCap(string value)
{
string result = String.Empty;
if(!String.IsNullOrEmpty(value))
{
if(value.Length == 1)
{
result = value.ToUpper();
}
else
{
result = value.Substring(0,1).ToString().ToUpper() + value.Substring(1).ToLower();
}
}
return result;
}
based on guffa's example above (slightly amended). you could convert that to an extension method (please pardon the badly named method :)):
public static string UpperFirst(this string source)
{
return source.ToLower().Remove(0, 1)
.Insert(0, source.Substring(0, 1).ToUpper());
}
usage:
var myNewString = myOldString.UpperFirst();
// or simply referenced as myOldString.UpperFirst() where required
cheers guffa
var initialString = "Hello hOW r u?";
var res = string.Concat(initialString..ToUpper().Substring(0, 1), initialString.ToLower().Substring(1));
You can use an extension method:
static class StringExtensions
{
public static string ToLowerFirst(this string text)
=> !string.IsNullOrEmpty(text)
? $"{text.Substring(0, 1).ToLower()}{text.Substring(1)}"
: text;
}
Unit tests as well (using FluentAssertions and Microsoft UnitTesting):
[TestClass]
public class StringExtensionsTests
{
[TestMethod]
public void ToLowerFirst_ShouldReturnCorrectValue()
=> "ABCD"
.ToLowerFirst()
.Should()
.Be("aBCD");
[TestMethod]
public void ToLowerFirst_WhenStringIsEmpty_ShouldReturnCorrectValue()
=> string.Empty
.ToLowerFirst()
.Should()
.Be(string.Empty);
}

Trim last character from a string

I have a string say
"Hello! world!"
I want to do a trim or a remove to take out the ! off world but not off Hello.
"Hello! world!".TrimEnd('!');
read more
EDIT:
What I've noticed in this type of questions that quite everyone suggest to remove the last char of given string. But this does not fulfill the definition of Trim method.
Trim - Removes all occurrences of
white space characters from the
beginning and end of this instance.
MSDN-Trim
Under this definition removing only last character from string is bad solution.
So if we want to "Trim last character from string" we should do something like this
Example as extension method:
public static class MyExtensions
{
public static string TrimLastCharacter(this String str)
{
if(String.IsNullOrEmpty(str)){
return str;
} else {
return str.TrimEnd(str[str.Length - 1]);
}
}
}
Note if you want to remove all characters of the same value i.e(!!!!)the method above removes all existences of '!' from the end of the string,
but if you want to remove only the last character you should use this :
else { return str.Remove(str.Length - 1); }
String withoutLast = yourString.Substring(0,(yourString.Length - 1));
if (yourString.Length > 1)
withoutLast = yourString.Substring(0, yourString.Length - 1);
or
if (yourString.Length > 1)
withoutLast = yourString.TrimEnd().Substring(0, yourString.Length - 1);
...in case you want to remove a non-whitespace character from the end.
The another example of trimming last character from a string:
string outputText = inputText.Remove(inputText.Length - 1, 1);
You can put it into an extension method and prevent it from null string, etc.
Try this:
return( (str).Remove(str.Length-1) );
In .NET 5 / C# 8:
You can write the code marked as the answer as:
public static class StringExtensions
{
public static string TrimLastCharacters(this string str) => string.IsNullOrEmpty(str) ? str : str.TrimEnd(str[^1]);
}
However, as mentioned in the answer, this removes all occurrences of that last character. If you only want to remove the last character you should instead do:
public static string RemoveLastCharacter(this string str) => string.IsNullOrEmpty(str) ? str : str[..^1];
A quick explanation for the new stuff in C# 8:
The ^ is called the "index from end operator". The .. is called the "range operator". ^1 is a shortcut for arr.length - 1. You can get all items after the first character of an array with arr[1..] or all items before the last with arr[..^1]. These are just a few quick examples. For more information, see https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8, "Indices and ranges" section.
string s1 = "Hello! world!";
string s2 = s1.Trim('!');
string helloOriginal = "Hello! World!";
string newString = helloOriginal.Substring(0,helloOriginal.LastIndexOf('!'));
string s1 = "Hello! world!"
string s2 = s1.Substring(0, s1.Length - 1);
Console.WriteLine(s1);
Console.WriteLine(s2);
Very easy and simple:
str = str.Remove( str.Length - 1 );
you could also use this:
public static class Extensions
{
public static string RemovePrefix(this string o, string prefix)
{
if (prefix == null) return o;
return !o.StartsWith(prefix) ? o : o.Remove(0, prefix.Length);
}
public static string RemoveSuffix(this string o, string suffix)
{
if(suffix == null) return o;
return !o.EndsWith(suffix) ? o : o.Remove(o.Length - suffix.Length, suffix.Length);
}
}
An example Extension class to simplify this: -
internal static class String
{
public static string TrimEndsCharacter(this string target, char character) => target?.TrimLeadingCharacter(character).TrimTrailingCharacter(character);
public static string TrimLeadingCharacter(this string target, char character) => Match(target?.Substring(0, 1), character) ? target.Remove(0,1) : target;
public static string TrimTrailingCharacter(this string target, char character) => Match(target?.Substring(target.Length - 1, 1), character) ? target.Substring(0, target.Length - 1) : target;
private static bool Match(string value, char character) => !string.IsNullOrEmpty(value) && value[0] == character;
}
Usage
"!Something!".TrimLeadingCharacter('X'); // Result '!Something!' (No Change)
"!Something!".TrimTrailingCharacter('S'); // Result '!Something!' (No Change)
"!Something!".TrimEndsCharacter('g'); // Result '!Something!' (No Change)
"!Something!".TrimLeadingCharacter('!'); // Result 'Something!' (1st Character removed)
"!Something!".TrimTrailingCharacter('!'); // Result '!Something' (Last Character removed)
"!Something!".TrimEndsCharacter('!'); // Result 'Something' (End Characters removed)
"!!Something!!".TrimLeadingCharacter('!'); // Result '!Something!!' (Only 1st instance removed)
"!!Something!!".TrimTrailingCharacter('!'); // Result '!!Something!' (Only Last instance removed)
"!!Something!!".TrimEndsCharacter('!'); // Result '!Something!' (Only End instances removed)
Slightly modified version of #Damian LeszczyƄski - Vash that will make sure that only a specific character will be removed.
public static class StringExtensions
{
public static string TrimLastCharacter(this string str, char character)
{
if (string.IsNullOrEmpty(str) || str[str.Length - 1] != character)
{
return str;
}
return str.Substring(0, str.Length - 1);
}
}
I took the path of writing an extension using the TrimEnd just because I was already using it inline and was happy with it...
i.e.:
static class Extensions
{
public static string RemoveLastChars(this String text, string suffix)
{
char[] trailingChars = suffix.ToCharArray();
if (suffix == null) return text;
return text.TrimEnd(trailingChars);
}
}
Make sure you include the namespace in your classes using the static class ;P and usage is:
string _ManagedLocationsOLAP = string.Empty;
_ManagedLocationsOLAP = _validManagedLocationIDs.RemoveLastChars(",");
If you want to remove the '!' character from a specific expression("world" in your case), then you can use this regular expression
string input = "Hello! world!";
string output = Regex.Replace(input, "(world)!", "$1", RegexOptions.Multiline | RegexOptions.Singleline);
// result: "Hello! world"
the $1 special character contains all the matching "world" expressions, and it is used to replace the original "world!" expression

Categories