Substring from character to character in C# - c#

How can I get sub-string from one specific character to another one?
For example if I have this format:
string someString = "1.7,2015-05-21T09:18:58;";
And I only want to get this part: 2015-05-21T09:18:58
How can I use Substring from , character to ; character?

If you string has always one , and one ; (and ; after your ,), you can use combination of IndexOf and Substring like;
string someString = "1.7,2015-05-21T09:18:58;";
int index1 = someString.IndexOf(',');
int index2 = someString.IndexOf(';');
someString = someString.Substring(index1 + 1, index2 - index1 - 1);
Console.WriteLine(someString); // 2015-05-21T09:18:58
Here a demonstration.

This would be better:
string input = "1.7,2015-05-21T09:18:58;";
string output = input.Split(',', ';')[1];
Using SubString:
public string FindStringInBetween(string Text, string FirstString, string LastString)
{
string STR = Text;
string STRFirst = FirstString;
string STRLast = LastString;
string FinalString;
int Pos1 = STR.IndexOf(FirstString) + FirstString.Length;
int Pos2 = STR.IndexOf(LastString);
FinalString = STR.Substring(Pos1, Pos2 - Pos1);
return FinalString;
}
Try:
string input = "1.7,2015-05-21T09:18:58;";
string output = FindStringInBetween(input, ",", ";");
Demo: DotNet Fiddle Demo

Use regex,
#"(?<=,).*?(?=;)"
This would extract all the chars next to , symbol upto the first semicolon.

Related

replace part of the string in C#

I have many strings which have multiple spaces and one forward slash like this:
string a="xxxxxx xxx xxxxxxxx xxxxxx aaa/xxxxxxxxxxxxxxx";
or
string b="xxxx xxx xxxxxx bbbbb/xxxxxxx xxx";
or
string c="xx xx 12345/x xx"
What I need to do is to replace the substring "aaa" or "bbbbb" or "12345" (Please note that the substrings are just examples, they can be anything) with the new string I want.
The feature for the substring "aaa" or "bbbbb" or "12345" or anything is that the substring is right before the only one forward slash and right after the space in front of and closest to this slash.
How do I locate this substring so that I can replace it with the new substring I want? Thanks.
Well, well well
Take your universal method:
public string Replacement(string input, string replacement)
{
string[] words = input.Split(' ');
string result = string.Empty;
for (int i = 0; i < words.Length; i++)
{
if(words[i].Contains('/'))
{
int barIndex = Reverse(words[i]).LastIndexOf('/') + 1;
int removeLenght = words[i].Substring(barIndex).Length;
words[i] = Reverse(words[i]);
words[i] = words[i].Remove(barIndex, removeLenght);
words[i] = words[i].Insert(barIndex, Reverse(replacement));
string ToReverse = words[i];
words[i] = Reverse(ToReverse);
break;
}
}
for(int i = 0; i < words.Length; i++)
{
result += words[i] + " ";
}
result = result.Remove(result.Length - 1);
return result;
}
public string Reverse(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
In reponse to >> I need a universal method to replace any stuff between the slash and the space closest to it
although a proposed answer is selected. I still decide to answer my own question.
string substr=""//any string I want
string a=OldString.split('/');//split by '/'
string b=a[0].Substring(0,a[0].LastIndexOf(' '));//get the substring before the last space
string NewString= b+ substr + a[1];//the substring between the space and the '/' is now replaced by substr
You should consider using a regex
Expression could be something like this "([^/]+)\\s(\\w+)/(.+)"
Regex.Replace (yourString, "([^/]+)\\s(\\w+)/(.+)", "$1 replacement/$3")
Regex.Replace
Use string.Replace("", "");
string a="xxxxxx xxx xxxxxxxx xxxxxx aaa/xxxxxxxxxxxxxxx";
string b="xxxx xxx xxxxxx bbbbb/xxxxxxx xxx";
string resultA = a.Replace("aaa", "Your replacement");
string resultB = b.Replace("bbbbb", "Your replacement");

Get string between a known string and any non-alphanumeric character

I have this code which allows me to get the string between "Global." and " ".
private string getGlobalVariableName(string text)
{
int pFrom = text.IndexOf("Global.") + "Global.".Length;
int pTo = text.LastIndexOf(" ");
string name = text.Substring(pFrom, pTo - pFrom);
return name;
}
I want to modify it so that it gets the string between "Global." and any non-alphanumeric character. How could I do this?
Example:
this is true for what I have now
getGlobalVariableName(" foo Global.bar1 foobar") == "bar1"
this is what I want to be able to do
getGlobalVariableName(" foo Global.bar1>foobar") == "bar1"
You can use Regex...
string input = "Global.bar1>foobar";
var output = Regex.Match(input, #"Global.([\w]+)").Groups[1].Value;

Trim a string in c# after special character

I want to trim a string after a special character..
Lets say the string is str="arjunmenon.uking". I want to get the characters after the . and ignore the rest. I.e the resultant string must be restr="uking".
How about:
string foo = str.EverythingAfter('.');
using:
public static string EverythingAfter(this string value, char c)
{
if(string.IsNullOrEmpty(value)) return value;
int idx = value.IndexOf(c);
return idx < 0 ? "" : value.Substring(idx + 1);
}
you can use like
string input = "arjunmenon.uking";
int index = input.LastIndexOf(".");
input = input.Substring(index+1, input.Split('.')[1].ToString().Length );
Use Split function
Try this
string[] restr = str.Split('.');
//restr[0] contains arjunmenon
//restr[1] contains uking
char special = '.';
var restr = str.Substring(str.IndexOf(special) + 1).Trim();
Try Regular Expression Language
using System.IO;
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string input = "arjunmenon.uking";
string pattern = #"[a-zA-Z0-9].*\.([a-zA-Z0-9].*)";
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine(match.Value);
if (match.Groups.Count > 1)
for (int ctr = 1; ctr < match.Groups.Count; ctr++)
Console.WriteLine(" Group {0}: {1}", ctr, match.Groups[ctr].Value);
}
}
}
Result:
arjunmenon.uking
Group 1: uking
Personally, I won't do the split and go for the index[1] in the resulting array, if you already know that your correct stuff is in index[1] in the splitted string, then why don't you just declare a constant with the value you wanted to "extract"?
After you make a Split, just get the last item in the array.
string separator = ".";
string text = "my.string.is.evil";
string[] parts = text.Split(separator);
string restr = parts[parts.length - 1];
The variable restr will be = "evil"
string str = "arjunmenon.uking";
string[] splitStr = str.Split('.');
string restr = splitStr[1];
Not like the methods that uses indexes, this one will allow you not to use the empty string verifications, and the presence of your special caracter, and will not raise exceptions when having empty strings or string that doesn't contain the special caracter:
string str = "arjunmenon.uking";
string restr = str.Split('.').Last();
You may find all the info you need here : http://msdn.microsoft.com/fr-fr/library/b873y76a(v=vs.110).aspx
cheers
I think the simplest way will be this:
string restr, str = "arjunmenon.uking";
restr = str.Substring(str.LastIndexOf('.') + 1);

Substring from different parts of a string

I have a string which contains white characters and I want to substring some values from it.
string mystring = "1. JoshTestLowdop 192";
(from 1. to J there's a whitespace)
string FirstNO = mystring.Substring(0, mystring.IndexOf(' '));
string Name = mystring.Substring(mystring.IndexOf(' '), mystring.LastIndexOf(' '));
string ID = mystring.Substring(mystring.LastIndexOf(' ');
But unfortunately the string Name also contains the number 1 from the 192 ..which shouldn't.
Can someone explain ..what's wrong?
Use String.Split method :
string mystring = "1. JoshTestLowdop 192";
var splitted = mystring.Split(new(){' '});
string FirstNo = splitted[0];
string name = splitted[1];
string ID = splitted[2];
This is assuming that the names don't contain white spaces as well.
The second argument to Substring is a "length" parameter, not the position in the string. You need to subtract the start position.
Also not that your current version contains the whitespace after "1.", so Name is actually " JoshTestLowdop". You need to add 1 to the first substring to get the actual name.
string mystring = "1. JoshTestLowdop 192";
int start = mystring.IndexOf(' ');
string FirstNO = mystring.Substring(0, start);
string Name = mystring.Substring(start + 1, mystring.LastIndexOf(' ') - (start + 1));
string ID = mystring.Substring(mystring.LastIndexOf(' ') + 1);
Console.WriteLine(FirstNO);
Console.WriteLine(Name);
Console.WriteLine(ID);
// outputs:
1.
JoshTestLowdop
192
The problem is with your second parameter to Substring function. It should be:
string Name = mystring.Substring(mystring.IndexOf(' '), mystring.LastIndexOf(' ')-mystring.IndexOf(' '));
You can try this:
string mystring = "1. JoshTestLowdop 192";
string[] strs = mystring.Split(' ');
string FirstNO =strs[0];
string Name = strs[1];
string ID = strs[2];

C# split string on X number of alpha numeric values

this might be simple question I have 3 strings
A123949DADWE2ASDASDW
ASDRWE234DS2334234234
ZXC234ASD43D33SDF23SDF
I want to split those by the first 8 characters and then the 10th and 11th and then combine them into one string.
So I would get:
A123949DWE
ASDRWE23S2
ZXC234AS3D
Basically the 9th character and anything after the 12th character is removed.
You can use String.Substring:
s = s.Substring(0, 8) + s[10] + s[11]
Example code:
string[] a = {
"A123949DADWE2ASDASDW",
"ASDRWE234DS2334234234",
"ZXC234ASD43D33SDF23SDF"
};
a = a.Select(s => s.Substring(0, 8) + s[10] + s[11]).ToArray();
Result:
A123949DWE
ASDRWE23S2
ZXC234AS3D
So let's say you have them declared as string variables:
string s1 = "A123949DADWE2ASDASDW";
string s2 = "ASDRWE234DS2334234234";
string s3 = "ZXC234ASD43D33SDF23SDF";
You can use the substring to get what you want:
string s1substring = s1.Substring(0,8) + s1.Substring(9,2);
string s2substring = s1.Substring(0,8) + s1.Substring(9,2);
string s3substring = s1.Substring(0,8) + s1.Substring(9,2);
And that should give you what you need. Just remember, that the string position is zero-based so you'll have to subtract one from the starting position.
So you could do:
string final1 = GetMyString("A123949DADWE2ASDASDW");
string final2 = GetMyString("ASDRWE234DS2334234234");
string final3 = GetMyString("ZXC234ASD43D33SDF23SDF");
public function GetMyString(string Original)
{
string result = Original.Substring(12);
result = result.Remove(9, 1);
return result;
}

Categories

Resources