简体   繁体   中英

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM