copy character from the string in c# - c#

Is there any way available to give start and ending value to the string and string copy all that values in c#
e.g
My name is testing.
Now i want to copy 'name is'
from the string how i can achieve. I don't have any specific length of the string, It could be increase and decrease.

Try String.IndexOf and String.Substring.
String s1 = "My name is testing.";
String sub = "name is";
int index = s1.IndexOf(sub);
String found = s2.Substring(index, sub.Length);

Well, I'm not completely sure what you are asking here, but...
I don't have any specific length of the string
Sure you do.
string s = "name is";
int len = s.Length; // len == 7
To concatenate strings you can use the + operator.
string prefix = "prefix : "
string suffix = "suffix : "
string s = prefix + "name is" + suffix;
int len = s.Length; // len == 25

I think I nailed your requirement and the solution. Do let me know if this is what you wanted and if this works!
MessageBox.Show(FindStringBetween("My name is farhan.", "My", "is"));
public string FindStringBetween(string SourceString, string StartString, string EndString)
{
int StartSelection = StartString.Length;
int EndSelection = SourceString.IndexOf(EndString)+EndString.Length;
return (SourceString.Substring(StartSelection).Substring(0, EndSelection-StartSelection));
}

Related

Retrieve and update the first number of a string

I have a string that may contain a prefix message with a number
e.g : Prefix1_SomeText
I need to check if the string contains the prefix message, and increment the number in that case.
Or if the string does not contain the prefix, I need to append it
e.g : Prefix2_SomeText.
So far I have this:
string format = "prefix{0}_";
string prefix = "prefix";
string text = "prefix1_65478516548";
if (!text.StartsWith(prefix))
{
text = text.Insert(0, string.Format(format, 1));
}
else
{
int count = int.Parse(text[6].ToString()) + 1;
text = (String.Format(format, count) + "_" + text.Substring(text.LastIndexOf('_') + 1));
}
Is there a simple way of doing it?
You could use a regular expression to check if the text contains the prefix and capture the index :
string prefix = "prefix";
string text = "prefix1_65478516548";
Regex r = new Regex($"{prefix}(\\d+)_(.*)");
var match = r.Match(text);
if (match.Success)
{
int index = int.Parse(match.Groups[1].Value);
text = $"{prefix}{index + 1}_{match.Groups[2].Value}";
}
else
{
text = $"{prefix}1_{text}";
}

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;

Substring from character to character in 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.

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);

strip out digits or letters at the most right of a string

I have a file name: kjrjh20111103-BATCH2242_20111113-091337.txt
I only need 091337, not the txt or the - how can I achieve that. It does not have to be 6 numbers it could be more or less but will always be after "-" and the last ones before ."doc" or ."txt"
You can either do this with a regex, or with simple string operations. For the latter:
int lastDash = text.LastIndexOf('-');
string afterDash = text.Substring(lastDash + 1);
int dot = afterDash.IndexOf('.');
string data = dot == -1 ? afterDash : afterDash.Substring(0, dot);
Personally I find this easier to understand and verify than a regular expression, but your mileage may vary.
String fileName = kjrjh20111103-BATCH2242_20111113-091337.txt;
String[] splitString = fileName.Split ( new char[] { '-', '.' } );
String Number = splitString[2];
Regex: .*-(?<num>[0-9]*). should do the job. num capture group contains your string.
The Regex would be:
string fileName = "kjrjh20111103-BATCH2242_20111113-091337.txt";
string fileMatch = Regex.Match(fileName, "(?<=-)\d+", RegexOptions.IgnoreCase).Value;
String fileName = "kjrjh20111103-BATCH2242_20111113-091337.txt";
var startIndex = fileName.LastIndexOf('-') + 1;
var length = fileName.LastIndexOf('.') - startIndex;
var output = fileName.Substring(startIndex, length);

Categories

Resources