String manipulation to truncate string up to a specified expression on C#
How do I remove more than three spaces from each line and end the string right there to look the line on the right using c#?
[Example1]
PO BOX XXX 开发者_开发问答 OVERDUE - PAY NOW
then transform to
PO BOX XXX
[Example2]
ClientB AMOUNT CARRI
then transform to
ClientB
[Example3]
PO BOX 400 FORWARD TO N
then transform to
PO BOX 400
var firstColumn = origString.SubString(0, origString.IndexOf(" "));
input = "PO BOX XXX OVERDUE - PAY NOW ";
input = input.Remove(input.IndexOf(" "));
there are 3 spaces in the indexOf paranthesis
Or you can do a split if you dont know if there is a tab or space -
input = input.Split(new char[] {' ', '\t'}, StringSplitOptions.RemoveEmptyEntries)[0];
You can do this:
var input = new string[3] { "PO BOX XXX OVERDUE - PAY NOW ",
"ClientB AMOUNT CARRI",
"PO BOX 400 FORWARD TO N "
};
for (int x = 0, len = input.Length; x != len; x++)
{
input[x] = Regex.Replace(input[x], @"\s{3}[^\n]+", string.Empty);
}
//input is ["PO BOX XXX","ClientB","PO BOX 400"]
Using linq:
var output = input.Select(str => Regex.Replace(str, @"\s{3}[^\r\n]+$", string.Empty));
if you're reading this string from file, you can do this:
var file = @"D:\file.txt";
var lines = File.ReadAllLines(file);
var output = lines.Select(str => Regex.Replace(str, @"\s{3}[^\n]+$", string.Empty)); // is ["PO BOX XXX","ClientB","PO BOX 400"]
You can use the string.Split method which results the string[]. Basing on the array count you can take the elements u need.
string base string = "PO BOX XXX OVERDUE - PAY NOW";
string[] delimittedStringArray = baseString.Split(' ');
if(delimittedStringArray.Length > 3)
{
// Take the data from array
}
else
{
// Do what ever
}
// I am not sure whether it is Length or Count in the if condition.
精彩评论