Substring from different parts of a string - c#

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

Related

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.

Replace all Special Characters including space with - using C#

I want to replace all Special Characters which can't be parse in URL including space, double space or any big space with '-' using C#.
I don't want to use any Parse Method like System.Web.HttpUtility.UrlEncode.
How to do this ? I want to include any number of space between two words with just one '-'.
For example, if string is Hello# , how are you?
Then, Result should be, Hello-how-are-you, no '-' if last index is any special character or space.
string str = "Hello# , how are you?";
string newstr = "";
//Checks for last character is special charact
var regexItem = new Regex("[^a-zA-Z0-9_.]+");
//remove last character if its special
if (regexItem.IsMatch(str[str.Length - 1].ToString()))
{
newstr = str.Remove(str.Length - 1);
}
string replacestr = Regex.Replace(newstr, "[^a-zA-Z0-9_]+", "-");
INPUT:
Hello# , how are you?
OUTPUT:
Hello-how-are-you
EDIT:
Wrap it inside a class
public static class StringCheck
{
public static string Checker()
{
string str = "Hello# , how are you?";
string newstr = null;
var regexItem = new Regex("[^a-zA-Z0-9_.]+");
if (regexItem.IsMatch(str[str.Length - 1].ToString()))
{
newstr = str.Remove(str.Length - 1);
}
string replacestr = Regex.Replace(newstr, "[^a-zA-Z0-9_]+", "-");
return replacestr;
}
}
and call like this,
string Result = StringCheck.Checker();
string[] arr1 = new string[] { " ", "#", "&" };
newString = oldString;
foreach repl in arr1
{
newString= newString.Replace(repl, "-");
}
Of course you can add into an array all of your spec characters, and looping trough that, not only the " ".
More about the replace method at the following link
You need two steps to remove last special character and to replace all the remaining one or more special characters with _
public static void Main()
{
string str = "Hello# , how are you?";
string remove = Regex.Replace(str, #"[\W_]$", "");
string result = Regex.Replace(remove, #"[\W_]+", "-");
Console.WriteLine(result);
Console.ReadLine();
}
IDEONE

SubString Text Selection

I'm using C#, and have the following string text value:
get directions from Sydney to Melbourne
And this is the code that I have at the moment to try and get the text that appears between From and To
String fromDestination = InputTextbox.Text;
if (fromDestination.Contains("from"))
{
fromDestination = fromDestination.Substring(fromDestination.IndexOf("from") + 5, fromDestination.IndexOf("to") - 3);
}
That code removes the word "from" from the returned value, but I cannot work out how to get ride of the "to". The output at the moment is:
sydney to Melb
Thanks for any help.
Here's another possible route (lolpun)..
You can split via "from" and "to". Each part is created for you then:
var str = "get directions from Sydney to Melbourne";
var parts = str.Split(new string[] { "from", "to" }, StringSplitOptions.None); // split it up
var from = parts[1]; // index 1 is from
var to = parts[2]; // index 2 is to
Console.WriteLine(from); // "Sydney"
Console.WriteLine(to); // "Melbourne"
The second parameter to pass to the Substring method is the number of chars to extract from the instance string, not another position
String fromDestination = InputTextbox.Text;
int pos = fromDestination.IndexOf(" from ");
if(pos >= 0)
{
int pos2 = fromDestination.IndexOf(" to ", pos);
if(pos2 > -1)
{
int len = pos2 - (pos + 6);
fromDestination = fromDestination.Substring(pos+6, len);
}
}
Notice that I have changed the search strings adding a space before and after from and to. This is a precautional measure required to avoid false positives when a city name contains 'to' as part of its name or if there is another from embedded in the text before the actual starting from
If the string is always the same I would suggest a simple string split.
string fromDestination = InputTextbox.Text.Split(' ')[3];
You can also use regular expressions:
String fromDestination = "get directions from Sydney to Melbourne";
var match = Regex.Match(fromDestination, #"(?<=from\s).*(?=\sto)");
if (match.Groups.Count > 0)
fromDestination = match.Groups[0].Value;
Substring(startIndex, length)
for compute the length you should try to fromDestination.Length - fromDestination.IndexOf(" to ")
fromDestination.Substring(fromDestination.IndexOf(" from ") + 5, fromDestination.Length - fromDestination.IndexOf(" to "));
This will get you the string "Sydney Melbourne":
string fromDestination = "get directions from Sydney to Melbourne";
string result = fromDestination.Substring(fromDestination.IndexOf("from") + 5).Replace("to", "");
By the look you probably would be better off replacing the textbox for 2 comboboxes,each with their items filled by a predefined list of available cities so the user cannot enter any typos for example and you just react to the selectedindex of the combobox...

how to get the substring

I have a string something like this 1234ABCD-1A-AB I have separator in string[] separator , I am looping till the length of string. I want to get the substring. inside the loop i am writing below code
string tempVar = test.Substring(0, test.IndexOf("'" + separator+ "'"));
I tried like this as well
string tempVar = String.Join(",", test.Split(',').Select(s => s.Substring(0, s.IndexOf("'" + separator+ "'"))));
by using this I am getting error Index should not be less that 0, Loop will run only 2 times because i am loop based on separator, and I have 2 separator in my string.
let me explain:
I have a loop for separator which will execute only 2 time because I'll 2 separator one is 9th position and other one is 14th positing, inside that loop I am splitting the string based on separator
string[] test1 = test.Split("'" + separator+ "'");
in my next step I am passing one string value for next process like this
string temp = test1[i].ToString();
with this i am getting only 2 string that is 1234ABCD and 1A I want to get the 3rd value as well inside the loop. So I thought of taking the substring than using split.
output should be:
first time: 1234ABCD
second time: 1A
third time: AB
You can use Split with your separator '-' and then access the returned string[].
string[] parts = test.Split('-');
string firstPart = parts[0];
string secondPart = parts.ElementAtOrDefault(1);
string thirdPart = parts.ElementAtOrDefault(2);
Demo
Use the split function:
string s = "1234ABCD-1A-AB";
string[] parts = s.Split('-');
then:
s[0] == "1234ABCD"
s[1] == "1A"
s[2] == "AB"
Based on the now updated requirements, try the following:
string input = "1234ABCD-1A-AB";
char separator = '-';
string[] parts = input.Split(separator);
// if you do not need to know the item index:
foreach (string item in parts)
{
// do something here with 'item'
}
// if you need to know the item index:
for (int i = 0; i < parts.Length; i++)
{
// do something here with 'item[i]', where i is
// the index (so 1, 2, or 3 in your case).
}
string[] items = str.Split(new char[] { '-' });
you can use String.Split():
string str = "1234ABCD-1A-AB";
string[] splitted = str.Split('-');
/* foreach (string item in splitted)
{
Console.WriteLine(item);
}*/
and you can set it as:
string firstPart = splitted.FirstOrDefault();
string secondPart = splitted.ElementAtOrDefault(1);
string thirdPart = splitted.ElementAtOrDefault(2);
You can use String.Split method
Returns a string array that contains the substrings in this instance
that are delimited by elements of a specified string or Unicode
character array.
string s = "1234ABCD-1A-AB";
string[] items = s.Split('-');
for(int i = 0; i < items.Length; i++)
Console.WriteLine("Item number {0} is: {1}", i, items[i]);
Output will be;
Item number 0 is: 1234ABCD
Item number 1 is: 1A
Item number 2 is: AB
Here is a DEMO.
I was only missing the index
string tempVar = test.Substring(0, test.IndexOf(separator[0].ToString()));
Very simple via String.Split():
string t = "1234ABCD-1A-AB";
string[] tempVar = t.Split('-');
foreach(string s in tempVar)
{
Console.WriteLine(s);
}
Console.Read();
Prints:
1234ABCD
1A
AB

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