Which method to use to remove string characters in stringBuilder class - c#

I would to know, Is there any method in StringBuilder class in C#, which can remove string characters without changing other character of same value within different index?
Like for a string like "5002", what if want to remove character in first index to "3"?
I'm using StringBuilder's remove method for the specified string and it's returning me an output as "5332" instead of "5302"?
The code which I'm using to accomplish my requirement is:
StringBuilder j = new StringBuilder("5002");
Console.WriteLine(j.Replace(j.ToString(1, 1),"3");

Well, you can use the indexer:
builder[1] = '3';
Is that what you're after?
For example:
using System;
using System.Text;
class Test
{
static void Main()
{
StringBuilder builder = new StringBuilder("5002");
builder[1] = '3';
Console.WriteLine(builder); // Prints 5302
}
}

Related

How to change string into a list of characters in C# for beginners?

I am currently trying to use Codecademy to learn how to use C# yet the last 'test' for the very second lesson asks us to convert a string to a list. I looked at a forum and it said you had to use loops which was not taught in the course yet, yet I wanted to use a loop anyway, how could I create the list with the for loop which possibly needs fixing? (And maybe help to check whether or not the other code is correct as it asks to convert bool to string and a random data type to another which I chose byte for.) Thanks.
bool pick = true;
byte number = 5;
string myTest = "Ping Pong";
Console.WriteLine(Convert.ToString(pick));
Console.WriteLine(Convert.ToInt32(number));
for ((char(myTest));)
{
Console.WriteLine(i);
}
You use string.ToCharArray to convert the string into an array of characters.
However you don't need to do that just to iterate over it, string implements IEnumerable<char>, so you can iterate over it directly.
Also for ((char(myTest));) makes absolutely no sense.
An string is already a character array and because System.String implements IEnumerable<char> you can just loop it:
/*
References you need:
using System;
using System.Collections.Generic;
using System.Linq;
*/
string myTest = "Ping Pong";
//looping a string
foreach (char character in myTest)
{
Console.WriteLine(character);
}
//Explicit converting a string to list of chars
var listChars = new List<char>();
listChars = myTest.ToList();
foreach (char character in listChars)
{
Console.WriteLine(character);
}

Reverse the letter case in a string using List

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.

How can I extract all non-alphanumeric characters from an input string using Regular Expressions?

Objective: To get all the non-alphanumeric characters even though they are not contiguous.
Setup: I have a textbox on an ASP.Net page that calls a C# code behind method on TextChanged. This event handler runs the textbox input against a Regex pattern.
Problem: I cannot create the proper Regex pattern that extracts all the non-alphanumeric characters.
This is the string input: string titleString = #"%2##$%^&";
These are the C# Regex Patterns that I have tried:
string titlePattern = #"(\b[^A-Za-z0-9]+)"; results with ##$%^& (Note: if I use this input string %2#35%^&, then the above regex pattern will identify the # sign, and then the %^&), but never the leading % sign).
string titlePattern = #"(\A[^A-Za-z0-9]+)"; results with %
string titlePattern = #"(\b\W[^A-Za-z0-9]+)"; results with ##$%^&
Side Note: I am also running this in a MS Visual Studio Console Application with a foreach loop in an effort to get all invalid characters into a collection and I also test the input and pattern using the web site: http://regexstorm.net/tester
Use the replace method with your selection string.
EDIT: After a closer reading I see that you wanted the opposite string. Here's both.
using System;
using System.Text.RegularExpressions;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
string Source = #"H)*e/.?l\l{}*o ][W!~`##""or^-_=+ld!";
string Trash = #"[^a-zA-Z0-9]";
string InvertedTrash = #"[a-zA-Z0-9]";
Output(Source, Trash);
Console.WriteLine($"{System.Environment.NewLine}Opposite Day!{System.Environment.NewLine}");
Output(Source, InvertedTrash);
Console.ReadKey();
}
static string TakeOutTheTrash(string Source, string Trash)
{
return (new Regex(Trash)).Replace(Source, string.Empty);
}
static void Output(string Source, string Trash)
{
string Sanitized = TakeOutTheTrash(Source, Trash);
Console.WriteLine($"Started with: {Source}");
Console.WriteLine($"Ended with: {Sanitized}");
}
}
}

C# json parse string inside 2nd curly brackets {X{Y}}

I try to parse string inside 2nd curly brackets using C# / json
String looks like this:
{"R27":{"DEVX":0.1346224}}
My aim is read value of DEVX, which is 0.1346224
I've tried:
var joR = JObject.Parse(R);
string R27 = joR["R27"].ToString();
RETURNS : {"DEVX":0.1346224}}
string R27 = joR["DEVX"].ToString();
RETURNS ERROR
Is there way to get directly value "0.1346224" without playing with string?
Yes, absolutely - assuming you know the two names involved, you can just index twice, once to get the object for R27, then once within that object to get the value of DEVX:
using System;
using Newtonsoft.Json.Linq;
public class Test
{
static void Main()
{
string json = "{\"R27\":{\"DEVX\":0.1346224}}";
var obj = JObject.Parse(json);
double devX = (double) obj["R27"]["DEVX"];
Console.WriteLine(devX);
}
}
var joR = JObject.Parse(R);
var R27 = joR["R27"]["DEVX"].ToString();

how to manipulate string which contains different pattern in C#?

i have a following type of string format ---
Proposal is given to {Jwala Vora#3/13} for {Amazon Vally#2/11} {1#3/75} by {MdOffice employee#1/1}
the string contains pair of { } with different positions and may be n number of times.
now i want to replace that pair with other strings which i will compute depending on the string between { } pair.
how to do this ?
You could try regular expressions. Specifically, Regex.Replace variants using MatchEvaluator should do the trick. See http://msdn.microsoft.com/en-US/library/cft8645c(v=vs.80).aspx for more information.
Something along these lines:
using System;
using System.Text.RegularExpressions;
public class Replacer
{
public string Replace(string input)
{
// The regular expression passed as the second argument to the Replace method
// matches strings in the format "{value0#value1/value2}", i.e. three strings
// separated by "#" and "/" all surrounded by braces.
var result = Regex.Replace(
input,
#"{(?<value0>[^#]+)#(?<value1>[^/]+)/(?<value2>[^}]+)}",
ReplaceMatchEvaluator);
return result;
}
private string ReplaceMatchEvaluator(Match m)
{
// m.Value contains the matched string including the braces.
// This method is invoked once per matching portion of the input string.
// We can then extract each of the named groups in order to access the
// substrings of each matching portion as follows:
var value0 = m.Groups["value0"].Value; // Contains first value, e.g. "Jwala Vora"
var value1 = m.Groups["value1"].Value; // Contains second value, e.g. "3"
var value2 = m.Groups["value2"].Value; // Contains third value, e.g. "13"
// Here we can do things like convert value1 and value2 to integers...
var intValue1 = Int32.Parse(value1);
var intValue2 = Int32.Parse(value2);
// etc.
// Here we return the value with which the matching portion is replaced.
// This would be some function of value0, value1 and value2 as well as
// any other data in the Replacer class.
return "xyz";
}
}
public static class Program
{
public static void Main(string[] args)
{
var replacer = new Replacer();
var result = replacer.Replace("Proposal is given to {Jwala Vora#3/13} for {Amazon Vally#2/11} {1#3/75} by {MdOffice employee#1/1}");
Console.WriteLine(result);
}
}
This program will output Proposal is given to xyz for xyz xyz by xyz.
You'll need to provide your app-specific logic in the ReplaceMatchEvaluator method to process value0, value1 and value2 as appropriate. The class Replacer can contain additional members that can be used to implement the replacement logic in ReplaceMatchEvaluator. Strings are processed by calling Replace on an instance of the Replacer class.
Well you can split the string by '{' and '}' and determine the contents that way.
But i think a better way would be to find the chars by index and then you know the starting index and the end index of a pair or curly brackets so that way you can reconstruct the string with the placeholders replaced.
But the best method may be using Regex.Replace but that will only help to replace the placeholders with values you want but i think your requirement is to also parse the text inside of the curly brackets and based on that chose the value to be inserted so this won't work well perhaps. Find and Replace a section of a string with wildcard type search
You may use the Regex.Replace Method (String, String, MatchEvaluator) method and the {.*?} pattern. The following example uses a dictionary to replace the values, but you may replace this with your own logic.
class Program
{
static Dictionary<string, string> _dict = new Dictionary<string, string>();
static void Main(string[] args)
{
_dict.Add("{Jwala Vora#3/13}","someValue1");
_dict.Add("{Amazon Vally#2/11}", "someValue2");
_dict.Add("{1#3/75}", "someValue3");
_dict.Add("{MdOffice employee#1/1}", "someValue4");
var input = #"Proposal is given to {Jwala Vora#3/13} for {Amazon Vally#2/11} {1#3/75} by {MdOffice employee#1/1}";
var result = Regex.Replace(input, #"{.*?}", Evaluate);
Console.WriteLine(result);
}
private static string Evaluate(Match match)
{
return _dict[match.Value];
}
}
Cannot you do something with string.Format()?
For example
string.Format("Proposal is given to {0} for {1} {2} by {3}", "Jwala Vora", "Amazon Vally", 1, "MdOffice employee");

Categories