String Manipulation and splitting string - c#

string url = "test:app:https://test#hotmail.co.uk:Test
I need to split this up to display as follows
string first = "app";
string second = "https://test#hotmail.co.uk:Test";
i have tried the following but falls over on the last colon.
string remove= "";
remove= url.Replace("test:", "");
string first= remove.Substring(remove.LastIndexOf(':') + 1);
string second= remove.Substring(0, remove.IndexOf(':'));
Doing this i get
first = "app";
second = "Test";
When i need
first = "app";
second = "https://test#hotmail.co.uk:Test";

Your use of LastIndexOf is just a bit wonky.
string url = "test:app:https://test#hotmail.co.uk:Test";
string remove = url.Replace("test:", "");
string first = remove.Substring(0, remove.IndexOf(":"));
string second = remove.Substring(remove.IndexOf(first) + first.Length + 1);
First grab the app, and we can use the location of app to derive the rest of the string. Because the last index of : would be the one in :Test. We don't want the last index of :. Instead we just want whatever comes after app.

As everything is prefixed with test: you can use a starting position after that and then split after the first occurrance of the : character.
const int IndexOfPrefix = 5; // start position after "test:"
string url = "test:app:https://test#hotmail.co.uk:Test";
var indexOfApp = url.IndexOf(':', IndexOfPrefix);
var part1 = url.Substring(IndexOfPrefix, indexOfApp - IndexOfPrefix);
var part2 = url.Substring(indexOfApp + 1);
Console.WriteLine(part1);
Console.WriteLine(part2);

Something like this should do the trick:
public void ManipulateStrings()
{
string url = "test:app:https://test#hotmail.co.uk:Test";
url = url.Replace("test:", "");
string first = url.Substring(0, url.IndexOf(':'));
string second = url.Substring(url.IndexOf(':') + 1);
}
This basically removed test: from your string, then assigns first and second their values without creating string remove = "" for no reason.

You can use Split(Char[], Int32) to get the desired number of elements (3 : the first unwanted part, the first expected part and the remaining) along with Skip() to remove the unwanted one :
string url = "test:app:https://test#hotmail.co.uk:Test";
var splitted = url.Split(new [] { ':' }, 3).Skip(1).ToArray();
var first = splitted[0];
var second = splitted[1];
Console.WriteLine(first);
Console.WriteLine(second);
This outputs
app
https://test#hotmail.co.uk:Test
Another way to do that is using regular expressions :
The pattern :(?<first>.*?):(?<second>.*) will :
: search for the characters :
(?<first>.*?) creates a group named first that will match any number of any character (lazy)
: search for the characters :
(?<second>.*) creates a group named second that will match any number of any character (greedy)
In example :
string url = "test:app:https://test#hotmail.co.uk:Test";
var pattern = ":(?<first>.*?):(?<second>.*)";
var regex = new Regex(pattern); // using System.Text.RegularExpressions;
Match match = regex.Match(url);
if (match.Success)
{
var first = match.Groups["first"].Value;
var second = match.Groups["second"].Value;
Console.WriteLine(first);
Console.WriteLine(second);
}
This outputs
app
https://test#hotmail.co.uk:Test

you need to change the variable with name "first" to "second" and to change the variable with name "second" to "first"
This is your code:
string url = "test:app:https://test#hotmail.co.uk:Test";
string remove = "";
remove = url.Replace("test:", "");
string second = remove.Substring(0, remove.IndexOf(':'));
string first = remove.Substring(remove.IndexOf(":") + 1);
and this is the correct code:
string url = "test:app:https://test#hotmail.co.uk:Test";
string remove = "";
remove = url.Replace("test:", "");
string first = remove.Substring(0, remove.IndexOf(':'));
string second = remove.Substring(remove.IndexOf(":") + 1);

Related

extract numerical values from string after dash (-)

I have string value like this Rs.100 - Rs.250 Now I want only 250 from this string.
I tried this but it's not getting output
var result = str.Substring(str.LastIndexOf('-') + 1);
UPDATE
string result = price.Text;
string[] final_result = result.Split('.');
dynamic get_result = final_result(1).ToString();
price.Text = final_result.ToString;
Try this code after getting the result of Rs.250.
var data = Regex.Match(result, #"\d+").Value;
Do it like this:
string str = "Rs.100-Rs.250";
var result = str.Substring(str.LastIndexOf('-') + 1);
String[] final_result = result.Split('.');
var get_result = final_result[1].ToString();
this will get 250 as you wanted.
try this
var result = ("Rs.100 - Rs.250").Split('-').LastOrDefault().Split('.').LastOrDefault();

dynamic substring in c#

I have a set of code in c# I want to store into the database what the user is entering in the textbox.
The user enters into the textbox like this
input namexyzpan9837663placeofbirthmumbailocationwadala
This is what user enters
(name: xyz pan: 9837663 place of birth: mumbai location: wadala)
Output into the database
xyz 9837663 mumbai wadala
OR
name xyzapan72placeofbirthgoalocationpanji
(> name: xyza pan: 72 place of birth: goa location: panji)
Output into the database
xyza 72 goa panji
name, age, location and placeofbirth are static but the value inside
them are dynamic
I know substring is helpfull but i don't know how to use it.
Use can use Split if the keywords are static :
string strMain = "namexyzpan9837663placeofbirthmumbailocationwadala";
var results = strMain.Split(new string[] { "name", "pan", "placeofbirth", "location" }, StringSplitOptions.RemoveEmptyEntries);
string name = results[0];
string pan = results[1];
string location = results[2];
You said you didn't know how to use Substring, well here it is working:
Note that the second parameter for this method is the length of the string to be taken and not the index at which to stop.
string strMain = "namexyzpan9837663placeofbirthmumbailocationwadala";
int indexOfName = strMain.IndexOf("name");
int indexOfPan = strMain.IndexOf("pan");
int indexOfBirth = strMain.IndexOf("placeofbirth");
int indexOflocation = strMain.IndexOf("location");
int effectiveIndexOfName = indexOfName + "name".Length;
int effectiveIndexOfPan = indexOfPan + "pan".Length;
int effectiveIndexOfBirth = indexOfBirth + "placeofbirth".Length;
int effectiveIndexOflocation = indexOflocation + "location".Length;
string name1 = strMain.Substring(effectiveIndexOfName, indexOfPan- effectiveIndexOfName);
string pan1 = strMain.Substring(effectiveIndexOfPan, indexOfBirth - effectiveIndexOfPan);
string birth1 = strMain.Substring(effectiveIndexOfBirth, indexOflocation - effectiveIndexOfBirth);
string location1 = strMain.Substring(effectiveIndexOflocation);
namenamepan9837663placeofbirthmumbailocationwadala works using the second method. But namepanpan9837663placeofbirthmumbailocationwadala is an interesting case that definitely needs a workaround.
Regex is designed for such case.
var input = #"namexyzpan9837663placeofbirthmumbailocationwadala";
var match = Regex.Match(input, #"^\s*"
+ #"name\s*(?<name>\w+?)\s*"
+ #"pan\s*(?<pan>\w+?)\s*"
+ #"placeofbirth\s*(?<placeOfBirth>\w+?)\s*"
+ #"location\s*(?<location>\w+)\s*" + #"$");
var name = match.Groups["name"].Value;
var pan = match.Groups["pan"].Value;
var placeOfBirth = match.Groups["placeOfBirth"].Value;
var location = match.Groups["location"].Value;

I want to split the data in the list when i see the ; in C#

I need to split this data in the box to and add it to new line when it see the ";"
var retryParamInfo = new ExParamsContent
{
Idenitifier = tempIdentifier.SerialNumber,
Name = String.Format( "Retry Information Console {0}",i),
Value = MyTestRunGlobals.FixtureComponents[i].Uuts[0].RetryList,
//Value = thisUut.RetryList.Replace("\n", "\n" + Environment.NewLine),
};
uutTempInfo.ExParams.Add(retryParamInfo);
To split a string when some character occours, you can use:
myString.split(';');
and make the result of this be inside a array.

Extract name and surname from string in c#

I need extract the name and surname from a email string.
In the database I have two type of address email working :
name.surname#xxxx.eu
Or
name.surname#xxxx.com
And I have tried this code :
string Email1 = Email.ToString().ToUpper().Replace("#", "");
if (Email1.Contains("XXXX.COM"))
{
Response.Write(Email1.ToString().Replace(".", " ").ToUpper().Remove(Email1.Length - 8, 8) + "<br />");
}
else
{
Response.Write(Email1.ToString().Replace(".", " ").ToUpper().Remove(Email1.Length - 7, 7) + "<br />");
}
This code not working for only these addresses emails :
VINCENT.NAPOLITAIN#XXXX.EU
because the return is :
VINCENT NAPOLITAINX
Not working for :
MARK.CHAIN#XXXX.COM
because the return is :
MARK CHAINX
Not working for :
NICODEMUS.ANGELICUM#XXXX.EU
because the return is :
NICODEMUS ANGELICUMX
How to do resolve this?
Please help me, thank you so much in advance.
why don't you split your address by the both seperator characters # and .
string email = "VINCENT.NAPOLITAIN#XXXX.EU";
string[] result = email.Split('.', '#').ToArray();
string firstname = result[0];
string lastname = result[1];
Simplistic approach (based on the requirements that you specified, which seem to be a bit strange):
var test = "name.surname#xxxx.eu";
var name = test.Substring(0, test.IndexOf('#')).Replace(".", " ");
Might want to add exception handling, of course.
You can use String.split():
string email = "VINCENT.NAPOLITAIN#XXXX.EU";
string names = email.Split('#')[0];
string name = "";
string surname = "";
if (names.Contains('.'))
{
var nameSurname = names.Split('.');
name = nameSurname[0]; //
surname = nameSurname[1];
}
You can use Regex Pattern:
(.+)\.(.+)(?=\#)
Explanation:
(.+) - Matches any character in a group
\. - Matches (.) dot
(?=\#) - Exclude # character
Code:
var match = Regex.Match(email, pattern);
var name = match.Groups[1].Value;
var surname = match.Groups[2].Value;
One option is to find the index of the . and the index of the # and do substrings on that:
string email = "aa.bb#cc.dd";
int periodIndex = email.IndexOf('.');
int atIndex = email.IndexOf('#');
string firstName = email.Substring(0, periodIndex);
string lastName = email.Substring(periodIndex + 1, atIndex - periodIndex - 1);
An easier way is to use a regular expression that cuts out the names.
This one will do:
(.*?)\.(.*?)#(.*)
The first capture is the first name, the second capture is the last name.
I would just use split in order to do it:
var nameDOTsurname = Email1.Split('#'); // This would leave in nameDOTsurname[0] the name.surname and in nameDOTsurname[1] the XXX.whatever
var name = nameDOTsurname[0].Split('.')[0];
var surname = nameDOTsurname[0].Split('.')[1];
This will work if your email address format sticks to firstname.secondname#wherever...
here is the code that works for you...
string e = "VINCENT.NAPOLITAIN#XXXX.EU";
string firstname = e.Substring(0, e.IndexOf("."));
string secondname = s.Substring(s.IndexOf(".")+1, s.IndexOf("#")-s.IndexOf(".")-1);
It works for all your emails

Grab a part of text when it matches, get rid of the rest because it's useless

I have a text called
string path = "Default/abc/cde/css/";
I want to compare a text.
string compare = "abc";
I want a result
string result = "Default/abc";
The rest of the path /cde/css is useless.Is it possible to grab the desire result in asp.net c#. Thanks.
Is this what you looking for?:
string result = path.Substring(0, path.IndexOf(compare)+compare.Length);
Try this. This will loop through the different levels (assuming these are directory levels) until it matches the compare, and then exit the loop. This means that if there is a folder called abcd, this won't end the loop.
string path = "Default/abc/cde/css";
string compare = "abc";
string result = string.Empty;
foreach (string lvl in path.Split("/")) {
result += lvl + "/";
if (lvl == compare)
{
break;
}
}
if (result.Length>0)
{
result = result.substring(0, result.length-1);
}
string path = "Default/abc/cde/css/";
string answer = "";
string compare = "abc";
if (path.Contains(compare ))
{
answer = path.Substring(0, path.IndexOf(stringToMatch) + compare.Length);
}
Something like the above should work.
I suggest that if you meet questions of this kind in the future, you should try it yourself first.
string result = path.Contains(compare) ? path.Substring(0, (path.IndexOf(compare) + compare.Length)) : path;

Categories