I thought this was simple but this is just kicking my butt.
I have this string 21. A.Person I simply want to get A.Person out of this.
I try the following but I only get 21
string[] pName = values[i, j].ToString().Split(new char[] { '.' }, 2);
pName[1] ???
values[i, j].ToString() = 21. A.Person and yes I've verified this.
Try this:
var substr="";
var indedx = yourString.IndexOf('.');
if(index>-1)
substr = yourString.Substring(index);
substr=substr.Trim();
For string "21. A.Person" should return "A.Person"
Everyone is giving you alternate solutions when yours should work.
The problem is that values[i, j] must not equal 21. A.Person
I plugged it into a simple test..
[Test]
public void junk()
{
string[] pName = "21. A.Person".Split(new char[] { '.' }, 2);
Console.WriteLine(pName[1]);
}
What does it print?
A.Person
(With the space in the front, because you didn't trim the space)
I would use substring() with the position of the first '.' as your start point:
var name = sourceString.Substring(sourceString.IndexOf('.'));
string pName = values[i, j].ToString().Substring(values[i, j].ToString().IndexOf('.')+1);
Try something like that:
var str = "21. A.Person";
var index = str.IndexOf('.') +1;
var substr = str.Substring(index, str.Length - index);
Related
For example I have those strings:
"qwe/qwe/qwe/qwe//qwe/somethinghere_blabla.exe"
"qwe/qwe/q//we/qwe//qwe/somethingother_here_blabla.exe"
"qwe/qwe/qwe/qwe//qwe/some_numbers_here_blabla.exe"
Now I want to get the text between the last '/' and the last '_'.
So the outcome would be:
"somethinghere"
"somethingother_here"
"some_numbers_here"
What is the easiest and clearest way to do this?
I have no idea how to do this, should I split them in '/' and '_', so do this apart? I couldn't think of any way how to do it.
Maybe scan the string from the end till it reaches its first '/' and '_'? Or is there an easier and faster way? Because it has to scan ~10.000 strings.
string[] words = line.Split('/', '_'); //maybe use this? probably not
Thanks in advance!
string s = "qwe/qwe/q//we/qwe//qwe/somethingother_here_blabla.exe";
int last_ = s.LastIndexOf('_');
if (last_ < 0) // _ not found, take the tail of string
last_ = s.Length;
int lastSlash = s.LastIndexOf('/');
string part = s.Substring(lastSlash + 1, last_ - lastSlash - 1);
Well, there is string.LastIndexOf:
var start = line.LastIndexOf('/') + 1;
var end = line.LastIndexOf('_');
var result = line.Substring(start, end - start);
The LINQ way:
var str = "qwe/qwe/qwe/qwe//qwe/somethinghere_blabla.exe";
var newStr = new string(str.Reverse().SkipWhile(c => c != '_').Skip(1).TakeWhile(c => c != '/').Reverse().ToArray());
var string = "qwe/qwe/qwe/qwe//qwe/some_numbers_here_blabla.exe";
var start = string.lastIndexOf("/");
var end = string.lastIndexOf("_");
var result = string.substring(start + 1, end);
Note: above code does not handle error if string does not have / or _ after a last slash
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...
I'm tring to remove the char '.' from a string except the last occurrence; for example the string
12.34.56.78
should became
123456.78
I'm using this loop:
while (value != null && value.Count(c => c == '.') > 1)
{
value = value.Substring(0, value.IndexOf('.')) + value.Substring(value.IndexOf('.') + 1);
}
I wonder if there is a cleaner way (maybe using linq?) to do this whitout an explicit loop?
(I know there is a very similar question but is about perl and things are quite different)
int lastIndex = value.LastIndexOf('.');
if (lastIndex > 0)
{
value = value.Substring(0, lastIndex).Replace(".", "")
+ value.Substring(lastIndex);
}
Perhaps a mixture of string methods and Linq:
string str = "12.34.56.78";
Char replaceChar = '.';
int lastIndex = str.LastIndexOf(replaceChar);
if (lastIndex != -1)
{
IEnumerable<Char> chars = str
.Where((c, i) => c != replaceChar || i == lastIndex);
str = new string(chars.ToArray());
}
Demo
I would do that way:
search for the last '.' ;
substring [0 .. indexOfLastDot] ;
remove in place any '.' of the substring
concatenate the substring with the rest of the original string, [indexOfLastDot .. remaining]
OR
search for the last '.'
for each enumerated char of the string
if it’s a '.' and i ≠ indexOfLastDot, remove it
var splitResult = v.Split(new char[] { '.' }).ToList();
var lastSplit = splitResult.Last();
splitResult.RemoveAt(splitResult.Count - 1);
var output = string.Join("", splitResult) + "." + lastSplit;
I would do it that way. The neatest way isn't always the shortest way.
Something like this should do the trick. Whether it is "good" or not is another matter. Note also that there is no error checking. Might want to check for null or empty string and that the string has at least one "." in it.
string numbers = "12.34.56.78";
var parts = String.Split(new char [] {'.'});
string newNumbers = String.Join("",parts.Take(parts.Length-1)
.Concat(".")
.Concat(parts.Last());
I don't claim that this would have great performance characteristics for long strings, but it does use Linq ;-)
you do not have to use loop:
//string val = "12345678";
string val = "12.34.56.78";
string ret = val;
int index = val.LastIndexOf(".");
if (index >= 0)
{
ret = val.Substring(0, index).Replace(".", "") + val.Substring(index);
}
Debug.WriteLine(ret);
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);
I want to trim the end off a string if it ends in ", ". That's a comma and a space.
I've tried TrimEnd(', '), but this doesn't work. It has to be only if the string ends this way, so I can't just use .Remove to remove the last two characters. How can I do it?
string txt = " testing, , ";
txt = txt.TrimEnd(',',' '); // txt = "testing"
This uses the overload TrimEnd(params char[] trimChars). You can specify 1 or more chars that will form the set of chars to remove. In this case comma and space.
This should work:
string s = "Bar, ";
if (s.EndsWith(", "))
s = s.Substring(0, s.Length - 2);
EDIT
Come to think of it, this would make a nice extension method:
public static String RemoveSuffix(this string value, string suffix)
{
if (value.EndsWith(suffix))
return value.Substring(0, value.Length - suffix.Length);
return value;
}
Try this:
string someText = "some text, ";
char[] charsToTrim = { ',', ' ' };
someText = someText.TrimEnd(charsToTrim);
Works for me.
The catch is that mystring.Trim(',') will only work if you reassign it to the string itself like this:
mystring = mystring.Trim(',')
"value, ".Trim().TrimEnd(",") should also work.
if (model != null && ModelState.IsValid)
{
var categoryCreate = new Categories
{
CategoryName = model.CategoryName.TrimStart().TrimEnd(),
Description = model.Description.TrimStart().TrimEnd()
};
_CategoriesService.Create(categoryCreate);
}
TrimStart().TrimEnd() == Left Trim and Right Trim