How do I replace specific characters from a c# string? - c#

if I have a string along the lines of: "user:jim;id:23;group:49st;"
how can I replace the group code (49st) with something else, so that it shows: "user:jim;id=23;group:76pm;"
sorry if the question is easy but I haven't found a specific answer, just cases different than mine.

You can use the index of "group" like this
string s = "user:jim;id:23;group:49st;";
string newS = s.Substring(0,s.IndexOf("group:") + 6);
string restOfS = s.IndexOf(";",s.IndexOf("group:") + 6) + 1 == s.Length
? ""
: s.Substring(s.IndexOf(";",s.IndexOf("group:") + 6) + 1);
newS += "76pm;";
s = newS + restOfS;
The line with the s = criteria ? true : false is essentially an if but it is put onto one line using a ternary operator.
Alternatively, if you know what text is there already and what it should be replaced with, you can just use a Replace
s = s.Replace("49st","76pm");
As an added precaution, if you are not always going to have this "group:" part in the string, to avoid errors put this inside an if which checks first
if(s.Contains("group:"))
{
//Code
}

Find the match using regex and replace it with new value in original string as mentioned below:
string str = "user:jim;id=23;group:49st;";
var match = Regex.Match(str, "group:.*;").ToString();
var newGroup = "group:76pm;";
str = str.Replace(match, newGroup);

This solution should work no matter where the group appears in the string:
string input = "user:jim;id:23;group:49st;";
string newGroup = "76pm";
string output = Regex.Replace(input, "(group:)([^;]*)", "${1}"+newGroup);

Here is a very generic method for splitting your input, changing items, then rejoining items to a string. It is not meant for single replacement in your example, but is meant to show how to split and join items in string.
I used Regex to split the items and then put results into a dictionary.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string pattern = "(?'name'[^:]):(?'value'.*)";
string input = "user:jim;id:23;group:49st";
Dictionary<string,string> dict = input.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => new
{
name = Regex.Match(x, pattern).Groups["name"].Value,
value = Regex.Match(x, pattern).Groups["value"].Value
}).GroupBy(x => x.name, y => y.value)
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
dict["group"] = "76pm";
string output = string.Join(";",dict.AsEnumerable().Select(x => string.Join(":", new string[] {x.Key, x.Value})).ToArray());
}
}
}

That is just one way to do it. I hope it will help you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace stringi
{
class Program
{
static void Main(string[] args)
{
//this is your original string
string s = "user:jim;id:23;group:49st";
//string with replace characters
string s2 = "76pm";
//convert string to char array so you can rewrite character
char[] c = s.ToCharArray(0, s.Length);
//asign characters to right place
c[21] = s2[0];
c[22] = s2[1];
c[23] = s2[2];
c[24] = s2[3];
//this is your new string
string new_s = new string(c);
//output your new string
Console.WriteLine(new_s);
Console.ReadLine();
}
}
}

string a = "user:jim;id:23;group:49st";
string b = a.Replace("49st", "76pm");
Console.Write(b);

Related

How can I remove the last two numbers from a number that's a double before making it a string?

I have this number in C#
Double a = 1.2345678
What I would like is for it to look like this after it's made into a string:
1.23456
First, convert it to string.
for example the string is defined as S.
then apply this method:
S.Remove(S.Length -2);
You can acheive that in many ways:
Code:
using System;
using System.Linq;
using System.Text;
namespace RemovingLastTwoNumber
{
class Program
{
static void Main(string[] args)
{
// Method 1.
double number = 1.2345678;
string numberInStringFormat = number.ToString();
string TargetNumber = numberInStringFormat.Substring(0, numberInStringFormat.Length - 2);
Console.WriteLine(number);
Console.WriteLine(TargetNumber);
// Method 2.
string _TargetNumber = Math.Round(number, 5).ToString();
Console.WriteLine(_TargetNumber);
// Method 3.
var characters = number.ToString().ToArray();
var __Characters = characters.Take(7);
StringBuilder __targetNumber = new StringBuilder();
foreach (var character in __Characters)
{
__targetNumber.Append(character);
}
Console.WriteLine(__targetNumber);
}
}
}

Split string into multiple alpha and numeric segments

I have a string like "ABCD232ERE44RR". How can I split it into separate segments by letters/numbers. I need:
Segment1: ABCD
Segment2: 232
Segment3: ERE
Segment4: 44
There could be any number of segments. I am thinking go Regex but don't understand how to write it properly
You can do it like this;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
var substrings = Regex.Split("ABCD232ERE44RR", #"[^A-Z0-9]+|(?<=[A-Z])(?=[0-9])|(?<=[0-9])(?=[A-Z])");
Console.WriteLine(string.Join(",",substrings));
}
}
Output : ABCD,232,ERE,44,RR
I suggest thinking of this as finding matches to a target pattern rather than splitting into the parts you want. Splitting gives significance to the delimiters whereas matching gives significance to the tokens.
You can use Regex.Matches:
Searches the specified input string for all occurrences of a specified regular expression.
var matches = Regex.Matches("ABCD232ERE44RR", "[A-Z]+|[0-9]+");
foreach (Match match in matches) {
Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index);
}
Try something like:
((A-Z)+(\d)*)+
If you decide not to use regex, you can always go the manual route.
const string str = "ABCD232ERE44RR1SGGSG3333GSDGSDG";
var result = new List<StringBuilder>
{
new StringBuilder()
};
char last = str[0];
result.Last().Append(last);
bool isLastNum = Char.IsNumber(last);
for (int i = 1; i < str.Length; i++)
{
char ch = str[i];
if (!((Char.IsDigit(ch) && isLastNum) || (Char.IsLetter(ch) && !isLastNum)))
{
result.Add(new StringBuilder());
}
result.Last().Append(ch);
last = ch;
isLastNum = Char.IsDigit(ch);
}

C# - Read between parentheses in RichTextBox

So I want to find out what is in between specific parentheses in a richtextbox. For example:
if (richTextBox1.Text.Contains("testname(") {
// Find what is in brackets of testname()
String outcome = //what is in brackets of testname()
}
This may be hard to understand, but let's say this is the richtextbox:
testname(name)
Then the string outcome would be name.
You can use regular expression to get the value between the parenthesis.
string text = richTextBox1.Text; // testname("some text")
string value = Regex.Match(text, #"\(([^)]*)\)").Groups[1].Value;
wrote from iPad so not tested, but something along these lines should get you there
String a = "testname(";
String b = "testname(Val)";
int x = b.IndexOf(a);
If (richTextBox1.Text.Contains(a)){
if (x != -1)
{
string final = b.Substring(x + a.Length);
}
}
string outcome = richTextBox1.Text;
outcome = outcome.Substring(outcome.IndexOf("(")+1, outcome.IndexOf(")") - outcome.IndexOf("("));
Regex would be the way to go.
Here I am matching exactly a parenthesis followed by any character one or more times followed by another parenthesis.
You have to escape parenthesis.
string yourText = richTextBox1.Text;
//string cow = "this is some text(this is the text you want)";
Regex regex = new Regex(#"\(.+\)");
Match match = regex.Match(yourText);
if (match.Success)
{
Console.WriteLine(match.Value); // with cow -> this is the text you want
} // can have else
You may want to consider using * instead of + in case they don't have any input between the ( ) Example: Regex regex = new Regex(#"\(.*\)");
Now it matches any character 0 or more times
You can achieve this with Linq and Regular Expressions.
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace Propress
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
string text = richTextBox1.Text;
ICollection<string> matches =
Regex.Matches(text.Replace(Environment.NewLine, ""), #"\(([^)]*)\)")
.Cast<Match>()
.Select(x => x.Groups[1].Value)
.ToList();
foreach (string match in matches)
MessageBox.Show(match);
}
}
}
string textBox = richTextBox1.Text;
textBox = textBox.Replace("testname(", "");
// Now textBox has the string you are looking for

String Replacement C#

Hope you can give me some light on this:
I have this var
string TestString = "KESRNAN FOREST S BV";
I want to replace the S that is alone, so I tried with the following
public static string FixStreetName(string streetName)
{
string result = "";
string stringToCheck = streetName.ToUpper();
// result = stringToCheck.Replace(StreetDirection(stringToCheck), "").Replace(StreetType(stringToCheck),"").Trim();
result = stringToCheck.Replace("S", "").Replace("BV", "").Trim();
return result;
}
But this is replacing all S on that string. any ideas?
Use regular expressions,
\b
denotes word boundaries. here is an example on C# Pad
string x = "KESRNAN FOREST S BV";
var result = System.Text.RegularExpressions.Regex.Replace(x, #"\bS\b", "");
Console.WriteLine(result);
If you can easily identify certain "delimiter" characters, one possibility is to 1. split your input string into several parts using string.Split; then 2. pick the parts that you want, and finally 3. "glue" them back together using string.Join:
var partsToExclude = new string[] { "S", "BV" };
/* 1. */ var parts = stringToCheck.Split(' ');
/* 2. */ var selectedParts = parts.Where(part => !partsToExclude.Contains(part));
/* 3. */ return string.Join(" ", selectedParts.ToArray());
Using Regex:
string input = "S KESRNAN FOREST S BV S";
string result = Regex.Replace(input, #"\b(S)", "");
As you can see alone S is before a space " ". In the other word have this string "S " which want to replace it.
Try this :
string TestString = "KESRNAN FOREST S BV";
string replacement = TestString.Replace("S ", "");
Another way of doing what you want:
using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string testString = "S KESRNAN S FOREST BV S";
// deleting S in middle of string
for (int i = 1; i < testString.Length-1; i++)
{
if (testString[i]=='S'&&testString[i-1]==' '&&testString[i+1]==' ')
testString=testString.Remove(i,2);
}
// deleting S in the begining of string
if (testString.StartsWith("S "))
testString = testString.Remove(0, 2);
// deleting S at the end of string
if (testString.EndsWith(" S"))
testString = testString.Remove(testString.Length-2, 2);
Console.WriteLine(testString);
}
}
}

Split string with ' in C#

How to split this string
1014,'0,1031,1032,1034,1035,1036',0,0,1,1,0,1,0,-1,1
and get this string array as result
1014
'0,1031,1032,1034,1035,1036'
0
0
1
1
0
1
0
-1
1
in C#
I believe that this regex should give you what you are looking for:
('(?:[^']|'')*'|[^',\r\n]*)(,|\r\n?|\n)?
http://regexr.com?2vib4
EDIT:
Quick code snippet on how it might work:
var rx = new Regex("('(?:[^']|'')*'|[^',\r\n]*)(,|\r\n?|\n)?");
var text= "1014,'0,1031,1032,1034,1035,1036',0,0,1,1,0,1,0,-1,1";
var matches = rx.Matches(text);
foreach (Match match in matches)
{
System.Console.WriteLine(match.Groups[1].ToString());
}
try this,
string line ="1014,'0,1031,1032,1034,1035,1036',0,0,1,1,0,1,0,-1,1" ;
var values = Regex.Matches(line, "(?:'(?<m>[^']*)')|(?<m>[^,]+)");
foreach (Match value in values) {
Console.WriteLine(value.Groups["m"].Value);
}
This code is not pretty at all, but it works. :) (Does not work with multiple "strings" within the string.)
void Main()
{
string stuff = "1014,'0,1031,1032,1034,1035,1036',0,0,1,1,0,1,0,-1,1";
List<string> newStuff = new List<string>();
var extract = stuff.Substring(stuff.IndexOf('\''), stuff.IndexOf('\'', stuff.IndexOf('\'') + 1) - stuff.IndexOf('\'') + 1);
var oldExtract = extract;
extract = extract.Replace(',',';');
stuff = stuff.Replace(oldExtract, extract);
newStuff.AddRange(stuff.Split(new[] {','}));
var newList = newStuff;
for(var i = 0; i < newList.Count; i++)
newList[i] = newList[i].Replace(';',',');
// And newList will be in the format you specified, but in a list..
}
Firstly split a string on ' (single) quote and then after go for comma (,).
You don't need a parser, you don't need Regex. Here's a pretty simple version that works perfectly:
var splits = input
.Split('\'')
.SelectMany(
(s,i) => (i%2==0)
? s.Split(new[]{','}, StringSplitOptions.RemoveEmptyEntries)
: new[]{ "'" + s + "'"}
);
This is exactly what #AVD + #Rawling described ... Split on ', and split only "even" results, then combine.
using System;
using System.IO;
using Microsoft.VisualBasic.FileIO; //Microsoft.VisualBasic.dll
public class Sample {
static void Main(){
string data = "1014,'0,1031,1032,1034,1035,1036',0,0,1,1,0,1,0,-1,1";
string[] fields = null;
data = data.Replace('\'', '"');
using(var csvReader = new TextFieldParser(new StringReader(data))){
csvReader.SetDelimiters(new string[] {","});
csvReader.HasFieldsEnclosedInQuotes = true;
fields = csvReader.ReadFields();
}
foreach(var item in fields){
Console.WriteLine("{0}",item);
}
}
}

Categories