How to delete a character from a string in console - c#

using System;
class Strng {
// Main Method
public static void Main()
{
// define string
String str = "Some_String";
Console.WriteLine("Given String : " + str);
// delete from index 5 to end of string
Console.WriteLine("New String1 : " + str.Remove(5));
// delete character from index 8 to end of string
Console.WriteLine("New String2 : " + str.Remove(8));
}
}
The above works with the given input but I want to give input dynamically and remove a character from given string dynamically

It looks like you're wanting to read dynamically a string and a character to replace.
You can do this with the use of Console.ReadLine() or Console.ReadKey()
Implementing the following into your main method:
Console.WriteLine("Enter a string:");
string s = Console.ReadLine();
Console.WriteLine("Enter a character to remove:");
string rs = Console.ReadLine().ToString();
//Assuming if they enter 'a' you want to remove both 'a' AND 'A':
string rsUpCase = rs.ToUpper();
string rsLoCase = rs.ToLower();
s = s.Replace(rsUpCase,"");
s = s.Replace(rsLoCase,"");
Console.WriteLine(s);
//Input:
//Aardvarks are boring creatures
//Result:
//rdvrks re boring cretures
Will allow a user to enter a string dynamically (not hard-coded) and remove any character taking advantage of the Replace function - also demonstrated is the use of upper/lower case to determine if you want both variants of a character to be removed.
Hope this helps.

I think the correct question is how to read from console.
You can use Console.Read() and Console.ReadLine().
First ask for the string, and then ask for the index to remove, if this is what you mean with dynamically
This is a MSDN Example about Read
using System;
class Sample
{
public static void Main()
{
string m1 = "\nType a string of text then press Enter. " +
"Type '+' anywhere in the text to quit:\n";
string m2 = "Character '{0}' is hexadecimal 0x{1:x4}.";
string m3 = "Character is hexadecimal 0x{0:x4}.";
char ch;
int x;
//
Console.WriteLine(m1);
do
{
x = Console.Read();
try
{
ch = Convert.ToChar(x);
if (Char.IsWhiteSpace(ch))
{
Console.WriteLine(m3, x);
if (ch == 0x0a)
Console.WriteLine(m1);
}
else
Console.WriteLine(m2, ch, x);
}
catch (OverflowException e)
{
Console.WriteLine("{0} Value read = {1}.", e.Message, x);
ch = Char.MinValue;
Console.WriteLine(m1);
}
} while (ch != '+');
}
}

Related

After instruction still can not make for loop with C# [duplicate]

This question already has answers here:
How do I create a terminable while loop in console application?
(7 answers)
Closed 3 years ago.
I started a C# course now and there is an assignment where I have to create a "palindrome detector" program. Point is that user inputs some word or sentence, then I have to remove chars like ,.;:!? and space from it. I have done that with two different methods, because char method can not remove space so I wrote another method for it.
After "cleaning" operation program reversing input what user gave, and comparing original user input and reversed user input to each other. It they are same it prints "It is palindrome", if they are different it prints "It is not palindrome". That is working fine, BUT THE PROBLEM IS I have to put them in for loop. It have to ask input again and again, until user give empty.
This would be very easy, but somehow I can not do it.
Here is my code:
using System;
namespace Palindromi
{
class Program
{
static void Main()
{
Console.WriteLine("Hei! Tervetuloa palindromin tunnistusohjelmaan. Tämä tunnistaa, onko syöttämäsi sana sama toisinpäin!");
Console.Write("Anna teksti (tyhjä lopettaa): ");
string userinput = Console.ReadLine(); //userinput is user's input, this is what you have to modify. remove some chars and reverse it.
if (userinput == "")
{
Console.ReadLine();//when i have loop this have to be "break". This meant to break for loop when i have it.
}
char[] removechars = { '.', ':', ';', ',', '!', '?' };//this is the list of "have to be removed" chars
string userinput_without_chars = userinput.Trim(removechars); //this method remove chars which are listed
string userinput_without_chars_space = userinput_without_chars.Replace( " ", ""); //replace space with empty
string reverse_string, reversed;
reverse_string = userinput_without_chars_space;
reversed = "";
int len;
len = userinput_without_chars_space.Length - 1;
while (len >= 0)
{
reversed = reversed + reverse_string[len];
len--;
}
Console.WriteLine("Sana käännettynä on {0}", reversed); //tells user input reversed
if (userinput_without_chars_space == reversed)//check is the userinput same than reversed user input
{
Console.Write("On palindromi.");//it is palindrome
}
else
{
Console.Write("Ei ole palindromi.");//it is not palindrome
}
}
}
}
You could potentially do something along these lines:
var running = true;
while(running)
{
var input = Console.ReadLine().ToLower();
var phrase = input.Sanitize(new List<string>() {".", ",", "?", "!", "'", "&", "%", "$", " "});
if(phrase.IsPalindrome())
Console.Writeline("Input was palindrome.");
}
public static string Sanitize(this string input, IList<string> punctuation) =>
String.Join(String.Empty, input.Where(character => punctuation.Contains(character) == false));
public static bool IsPalindrome(this string sentence)
{
for (int l = 0, r = sentence.Length - 1; l < r; l++, r--)
if (sentence[l] != sentence[r])
return false;
return true;
}
public static void Close(string input)
{
// Some logic to see if the application should stop.
}
You could create another method that looks for commands, or keystrokes, then sets the boolean to run as false. Which would break the infinite loop. You could also do an abrupt close with Environment.Exit.
The very simplest approach is replace your Console.ReadLine() where you want to break to return.
Alternatively, you could wrap the logic in another while loop.
while (userinput != "")
{
// Remove chars
// rest of your logic
/* IMPORTANT */
userinput = Console.Readline();
}
To remove the symbols from the input, you can use the Regex.Replace method. In this case, you can be sure, that the specified symbols will be correctly removed from the input string. Note, that you can handle the whitespaces along with other characters you mentioned, like in the code snippet below:
var CharactersToRemove { get; set; } = " ,.;:!?";
var processedInput = Regex.Replace(input.ToLower(), $"[{CharactersToRemove}]", string.Empty);
Note, that here I used input.ToLower() to convert the input to a lowercase string. This will make the palindrome tests case-insensitive. Should you need case-sensitive palindrome tests, just remove the .ToLower() part.
There is no need to reverse the input string to check if it is a palindrome. You can check this within one for loop as follows:
bool CheckForBeingaAPalindrome(string input)
{
var frontIndex = 0;
var tailIndex = input.Length - 1;
for (; frontIndex < tailIndex;)
{
if (input[frontIndex] != input[tailIndex])
return false;
++frontIndex;
--tailIndex;
}
return true;
}
Note, that in this case you only iterate over the elements of the input string once. This approach will give you al least 4 times better performance than the one you used.
Below, you can find a complete minimal working solution to your problem.
using System.Text.RegularExpressions;
using static System.Console;
namespace Assignment
{
public static class PalindromeFinder
{
public static string CharactersToRemove { get; set; } = " ,.;:!?";
public static bool IsPalindrome(string input)
{
var processedInput = RemoveUnnecessaryCharacters(input);
return CheckForBeingAPalindrome(processedInput);
}
private static string RemoveUnnecessaryCharacters(string input)
{
return Regex.Replace(input.ToLower(), $"[{CharactersToRemove}]", string.Empty);
}
private static bool CheckForBeingAPalindrome(string input)
{
var frontIndex = 0;
var tailIndex = input.Length - 1;
for (; frontIndex < tailIndex;)
{
if (input[frontIndex] != input[tailIndex])
return false;
++frontIndex;
--tailIndex;
}
return true;
}
}
public class Program
{
private static void Main(string[] args)
{
ContinuouslyCheckUserInputForBeingAPalindrome();
}
private static void ContinuouslyCheckUserInputForBeingAPalindrome()
{
while (FetchUserInputFromConsole() is string input
&& !string.IsNullOrWhiteSpace(input))
{
var isPalindrome = PalindromeFinder.IsPalindrome(input);
var modifier = isPalindrome ? "a" : "not a";
WriteLine($"It is {modifier} palindrome");
}
}
private static string FetchUserInputFromConsole()
{
Write("Enter a string: ");
return ReadLine();
}
}
}

How to correctly convert letters to numbers?

I have a string which comprise lots of letters. I have used the following code to convert it to numbers, but the new string t still gives me imperfect result.
For example:
tung2003 -> -1-1-1-12003
What I expected: 1161171101032003 (116 is the ASCII code of t, 117 is the ASCII code of u
string t=null;
foreach (char c in Properties.Settings.Default.password)
{
int ascii = (int)Char.GetNumericValue(c);
int counter=0;
counter = ascii;
t = t + Convert.ToString(counter);
}
The problem is the - character. I want my new string only comprises numbers.
It looks like you do not want the ASCII values of the numbers based on your expected output. In that case you can just do something like this:
string input = "tung2003";
string output = string.Empty;
foreach(char c in input)
{
if(char.IsNumber(c))
{
output += c;
}
else
{
output += ((byte)c).ToString();
}
}
//output is now: 1161171101032003
Fiddle here
Also added as a Linq expression for a short hand solution.
// Method 1 Linq
string output = string.Concat(("tung2003".ToCharArray()
.Select(s=> char.IsDigit(s) ? s.ToString() : ((int)s).ToString())));
// Method 2
string input = "tung2003";
string output = string.Empty;
foreach (char c in input)
{
if (Char.IsDigit(c)) output += c.ToString();
else output += ((int)c).ToString();
}
Extrapolating your output it looks like you want two different things. You want to tally each ascii character as long as it is a letter and extract the numeric values to append. The following provides three options, the first is to tally the ascii values from letters and the other two are ways to extract only digits. Because your code example uses a Password I am assuming you are trying to do some sort of custom hashing and if that is the case you should use a Hash implementation from the Cryptography namespace or some other package.
using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
var combined = OnlyLettersToAscii("tung2003") + OnlyNumbers("tung2003");
Console.WriteLine($"Input: tung2003 Output: {OnlyNumbers("tung2003")}");
Console.WriteLine($"Input: tung2003 Output Regex: {OnlyNumbersWithRegex("tung2003")}");
Console.ReadKey();
}
private static string OnlyLettersToAscii(string originalString)
{
if (string.IsNullOrWhiteSpace(originalString)) return originalString;
return string.Join(string.Empty, originalString.ToArray()
.Where(w => char.IsLetter(w))
.Select(s => ((int)s).ToString()));
}
private static string OnlyNumbers(string originalString)
{
if (string.IsNullOrWhiteSpace(originalString)) return originalString;
return new string(originalString.Where(w => char.IsDigit(w)).ToArray());
}
public static string OnlyNumbersWithRegex(string originalString)
{
return Regex.Replace(originalString, #"[^\d]", string.Empty);
}
}
}
string t = "";
foreach (char c in Properties.Settings.Default.password)
{
if (IsNumber(x)) t += System.Convert.ToInt32(c).ToString();
else
{
t += c.ToString();
}
}
Moreover, if you just want to get rid off '-' the use this code: t =String.Replace(t, '-');

Checking if string contains numeric value, then display the value doubled

user input:
"I have 3 apples"
output:
"I"
"have"
"6"
"apples"
My C#:
static void Main(string[] args)
{
Console.WriteLine("Enter a string...");
string delimeter = " ";
string input = Console.ReadLine();
string[] output = input.Split(Convert.ToChar(delimeter));
foreach (var substring in output)
{
Console.WriteLine(substring);
}
Console.Read();
}
I need help getting on the right track. My code only breaks the sentence apart using space as a delimiter.
Give it a try
foreach (var substring in output)
{
int value;
if(int.TryParse(substring, out value)){
value = value * 2;
input = input.Replace(substring, value.ToString());
}
}
Console.WriteLine(input);
You first need to check if your spitted string is a number, if it is then multiple by 2 and replace it in your input variable to get the expected output.
Can you try followoing?
static void Main(string[] args)
{
Console.WriteLine("Enter a string...");
string delimeter = " ";
string input = Console.ReadLine();
var result = System.Text.RegularExpression.Regex.Replace(input,"\d+", match=>(int.Parse(match.Value)*2).ToString(CultureInfo.InvariantCul‌​ture));
Console.WriteLine(result);
Console.Read();
}
Here is an algorithm for example.
// an extension method to check if a string is all decimal digits
public static class StringHelper {
public static bool IsNumeric(this string str)
{
if (str.IsNullOrWhiteSpace()) return false;
return str.All(char.IsNumber);
}
}
...
static void Main(string[] args)
{
Console.WriteLine("Enter a string...");
string delimeter = " ";
string input = Console.ReadLine();
string[] output = input.Split(Convert.ToChar(delimeter));
foreach (var substring in output)
{
if (substring.IsNumeric())
{
substring = (int.Parse(substring) * 2).ToString();
}
Console.Write(substring);
}
Console.WriteLine();
Console.Read();
}
Please note that the code is only checking if a substring contains only decimal digits. It's not prepared to handle any number with decimal point for example, and it's also not completely safe. The code is not tested, and is ment only for example purposes.
I intentionally showed a code without using Regular Expressions, but if you're interested, check out the other answers for that alternative.

Remove all characters after the last letter

The following simple program will find the last letter in a string that a user enters and then remove everything after that point. So, if a person enters one string.... everything after the g should be removed. I've got the following as a little program:
class Program
{
static void Main(string[] args)
{
Console.Write("Enter in the value of the string: ");
List<char> charList = Console.ReadLine().Trim().ToList();
int x = charList.LastIndexOf(charList.Last(char.IsLetter)) ;
Console.WriteLine("this is the last letter {0}", x);
Console.WriteLine("This is the length of the string {0}", charList.Count);
Console.WriteLine("We should have the last {0} characters removed", charList.Count - x);
for (int i = x; i < charList.Count; i++)
{
charList.Remove(charList[i]);
}
foreach (char c in charList)
{
Console.Write(c);
}
Console.ReadLine();
}
}
I've tried numerous variations of this and none of them getting it exactly write. This particular program with an input of string.... the output of the program is strin.. So somehow it's leaving on what it should be taking away and it's actually taking away letters that it shouldn't. Can anyone give an indication as to why this is happening? The desired output, again should be string.
Try this:
string input = Console.ReadLine(); // ABC.ABC.
int index = input.Select((c, i) => new { c, i })
.Where(x => char.IsLetter(x.c))
.Max(x => x.i);
string trimmedInput = input.Substring(0, index + 1);
Console.WriteLine(trimmedInput); // ABC.ABC
Jsut for the explanation, that's because each time you remove a character, you increment the i counter but also decrementing charList.Count so you're actually removing 1 character, leaving the next one, then removing again and so on...
For example, with the input "string...." and x being 5 (index of the G letter) you're doing :
1st iteration :
Remove the g char so x becomes 6 and charList.Count becomes 9 (10-1)
Next iteration :
Remove the char at index 6 which is now the second . (your string being "strin....").
So you missed the first point.
I let you check other answers as they contains more elegant solutions for your problems.
I think it would be a lot more straight forward to simply Substring the string the user entered. So consider the following modified code:
class Program
{
static void Main(string[] args)
{
Console.Write("Enter in the value of the string: ");
var s = Console.ReadLine().Trim();
List<char> charList = s.ToList();
int x = charList.LastIndexOf(charList.Last(char.IsLetter)) ;
Console.WriteLine("this is the last letter {0}", x);
Console.WriteLine("This is the length of the string {0}", charList.Count);
Console.WriteLine("We should have the last {0} characters removed", charList.Count - x);
Console.WriteLine(s.Substring(0, x + 1);
Console.ReadLine();
}
}
here we store the value the user entered into s, find the last index of a letter, and then Substring through that letter when writing out to the console.
string s = console.ReadLine();
s = s.Substring(0, s.ToList().FindLastIndex(char.IsLetter) + 1);
You also can use a function of string called SubString, to get everything from the first to the last letter index.
Here's a pretty inefficient way to do it (just for fun!)
var trimmedInput = string.Join("", input.Reverse().SkipWhile(x => !char.IsLetter(x)).Reverse());
You could use this extension:
public static string TrimLettersLeft(this string input)
{
int lastLetterIndex = -1;
for (int i = input.Length - 1; i >= 0; i--)
{
if (Char.IsLetter(input[i]))
{
lastLetterIndex = i;
break;
}
}
if( lastLetterIndex == -1)
return input;
else
return input.Substring(0, lastLetterIndex + 1);
}
Input: test...abc...
Output: test...abc
DEMO
Solution will be like this.
string charList = "string..."; //any string place here
int x = charList.LastIndexOf(charList.Last(char.IsLetter));
String str = charList.ToString().Substring(0, x + 1);
This will match every word character (A-Z, 0-9 and _):
string Input = Console.ReadLine();
string Userinput = String.Empty;
Regex TextSearch = new Regex(#"\w*");
if(TextSearch.IsMatch(Input))
Userinput = TextSearch.Match(Input).Groups[0].Value;
else
// No valid Input
What I believe would be the shortest, simplest option:
Edit: A comment pointed out an initial error here, so I added a little fix. Should work nicely now (might not be the optimal solution, but I thought it was a fun an simple solution anyway):
var userInput = Console.ReadLine();
Console.WriteLine(new string(userInput.Reverse()
.SkipWhile(c => !char.IsLetter(c))
.Reverse()
.ToArray()));

C# fix sentence

I need to take a sentence in that is all on one line with no spaces and each new word has a captial letter EX. "StopAndSmellTheRoses" and then convert it to "Stop and smell the roses" This is my function that I have but I keep getting an argument out of range error on the insert method. Thanks for any help in advance.
private void FixSentence()
{
// String to hold our sentence in trim at same time
string sentence = txtSentence.Text.Trim();
// loop through the string
for (int i = 0; i < sentence.Length; i++)
{
if (char.IsUpper(sentence, i) & sentence[i] != 0)
{
// Change to lowercase
char.ToLower(sentence[i]);
// Insert space behind the character
// This is where I get my error
sentence = sentence.Insert(i-1, " ");
}
}
// Show our Fixed Sentence
lblFixed.Text = "";
lblFixed.Text = "Fixed: " + sentence;
}
The best way to build up a String in this manner is to use a StringBuilder instance.
var sentence = txtSentence.Text.Trim();
var builder = new StringBuilder();
foreach (var cur in sentence) {
if (Char.IsUpper(cur) && builder.Length != 0) {
builder.Append(' ');
}
builder.Append(cur);
}
// Show our Fixed Sentence
lblFixed.Text = "";
lblFixed.Text = "Fixed: " + builder.ToString();
Using the Insert method creates a new string instance every time resulting in a lot of needlessly allocated values. The StringBuilder though won't actually allocate a String until you call the ToString method.
You can't modify the sentence variable in the loop that is going through it.
Instead, you need to have a second string variable that you append all of the found words.
Here is the answer
var finalstr = Regex.Replace(
"StopAndSmellTheRoses",
"(?<=[a-z])(?<x>[A-Z])|(?<=.)(?<x>[A-Z])(?=[a-z])|(?<=[^0-9])(?<x>[0-9])(?=.)",
me => " " + me.Value.ToLower()
);
will output
Stop and smell the roses
Another version:
public static class StringExtensions
{
public static string FixSentence(this string instance)
{
char[] capitals = Enumerable.Range(65, 26).Select(x => (char)x).ToArray();
string[] words = instance.Split(capitals);
string result = string.Join(' ', words);
return char.ToUpper(result[0]) + result.Substring(1).ToLower();
}
}

Categories

Resources