SubString Text Selection - c#

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...

Related

How can I add a space between every 3 characters counting from the right to the left in a string in C#?

I want to add space between every 3 characters in a string in C#, but count from right to left.
For example :
11222333 -> 11 222 333
Answer by #Jimi from comments (will delete if they post their own)
var YourString = "11222333";
var sb = new StringBuilder(YourString);
for (int i = sb.Length -3; i >= 0; i -= 3)
sb.Insert(i, ' ');
return sb.ToString();
The benefit of this algorithm appears to be that you are working backwards through the string and therefore only moving a certain amount on each run, rather than the whole string.
If you are trying to format a string as a number according to some locale conventions you can use the NumberFormat class to set how you want a number to be formatted as a string
So for example
string input = "11222333";
NumberFormatInfo currentFormat = new NumberFormatInfo();
currentFormat.NumberGroupSeparator = " ";
if(Int32.TryParse(input, NumberStyles.None, currentFormat, out int result))
{
string output = result.ToString("N0", currentFormat);
Console.WriteLine(output); // 11 222 333
}
The following recursive function would do the job:
string space3(string s)
{
int len3 = s.Length - 3;
return (len <= 0) ? s
: (space3(s.Substring(0, len3)) + " " + s.Substring(len3));
}
C# 8.0 introduced string ranges. Ranges allow for a more compact form:
string space3(string s)
{
return (s.Length <= 3) ? s
: (space3(s[..^3]) + " " + s[^3..]);
}
Using Regex.Replace:
string input = "11222333";
string result = Regex.Replace( input, #"\d{3}", #" $0", RegexOptions.RightToLeft );
Demo and detailed explanation of RegEx pattern at regex101.
tl;dr: Match groups of 3 digits from right to left and replace them by space + the 3 digits.
The most efficient algorithm I can come up with is the following:
var sb = new StringBuilder(YourString.Length + YourString.Length / 3 + 1);
if (YourString.Length % 3 > 0)
{
sb.Append(YourString, 0, YourString.Length % 3);
sb.Append(' ');
}
for (var i = YourString.Length % 3; i < YourString.Length; i += 3)
{
sb.Append(YourString, i, 3);
sb.Append(' ');
}
return sb.ToString();
We first assign a StringBuilder of the correct size.
Then we check to see if we need to append the first one or two characters. Then we loop the rest.
dotnetfiddle

how to split string by position c#

I have a text string that when it exceeds a specific length, I separate the string into 2 strings, passing the rest of the remaining content to another variable, but I have an exception
Index and length must refer to a location within the string. (Parameter 'length')
My C# code:
string text = "Hello word jeje";
if (text.Length > 10)
{
string stringOne = text.Substring(0, 10);
string stringTwo = text.Substring(11, text.Length); //throw exception
}
expected result:
string text = "Hello word jeje";
string stringOne = "Hello";
string stringTwo = " jeje";
You have an off-by-one error; you'd need text.Length - 1.
The two-argument version of String.Substring() accepts start and length arguments; you'd need text.Substring(11, text.Length - 11).
However, you can just leave the second argument off for the second half, since the single-argument version of String.Substring() returns a substring to the end of the string.
string stringOne = text.Substring(0, 10);
string stringTwo = text.Substring(11);
How about using the Linq Chunk() extension method?
var test = "Hello World Yeah";
var chunks = test.Chunk(10);
foreach (var chunk in chunks)
{
var subtext = new string(chunk.ToArray());
Console.WriteLine(subtext);
}
Output:
Hello Worl
d Yeah

How to replace a particular character from string in c#?

I have a string like AX_1234X_12345_X_CXY, I want to remove X from after the first underscore _ i.e. from 1234X to 1234. So final output will be like AX_1234_12345_X_CXY. How to do it?? If I use .Replace("X", "") it will replace all X which I don't want
You can iterate trough the string from the first occurrence of '_' .
you can find the first occurrence of '_' using IndexOf().
when loop will get to 'X' it will not append it to the "fixed string".
private static void Func()
{
string Original = "AX_1234X_12345_X_CXY";
string Fixed = Original.Substring(0, Original.IndexOf("_", 0));
// in case you want to remove all 'X`s' after first occurrence of `'_'`
// just dont use that variable
bool found = false;
for (int i = Original.IndexOf("_", 0); i < Original.Length; i++)
{
if (Original[i].ToString()=="X" && found == false)
{
found = true;
}
else
{
Fixed += Original[i];
}
}
Console.WriteLine(Fixed);
Console.ReadLine();
}
Why not good old IndexOf and Substring?
string s = "AX_1234X_12345_X_CXY";
int pUnder = s.IndexOf('_');
if (pUnder >= 0) { // we have underscope...
int pX = s.IndexOf('X', pUnder + 1); // we should search for X after the underscope
if (pX >= 0) // ...as well as X after the underscope
s = s.Substring(0, pX) + s.Substring(pX + 1);
}
Console.Write(s);
Outcome:
AX_1234_12345_X_CXY
string original = #"AX_1234X_12345_X_CXY";
original = #"AX_1234_12345_X_CXY";
One way is String.Remove, because you can tell exactly where to remove from. If the offending "X" is always in the same place, you can use:
string newString = old.Remove(7,1);
This will remove 1 character starting as position 7 (counting from zero as the beginning of the string).
If not always in the same character position, you might try:
int xPos = old.IndexOf("X");
string newString = old.Remove(xPos,1);
EDIT:
Based on OP comment, the "X" we're targeting occurs just after the first underscore character, so let's index off of the first underscore:
int iPosUnderscore = old.IndexOf("_");
string newString = old.Remove(iPosUnderscore + 1 ,1); // start after the underscore
Try looking at string.IndexOf or string.IndexOfAny
string s = "AX_1234X_12345_X_CXY";
string ns = HappyChap(s);
public string HappyChap(string value)
{
int start = value.IndexOf("X_");
int next = start;
next = value.IndexOf("X_", start + 1);
if (next > 0)
{
value = value.Remove(next, 1);
}
return value;
}
If and only if this is always the format then it should be a simple matter of combining substrings of the original text without including the x in that position. But the op hasn't stated that this is always the case. So if this is always the format and the same character position is always removed then you could simply just
string s = "AX_1234X_12345_X_CXY";
string newstring = s.Substring(0, 7) + s.Substring(8);
OK, based on only the second set of numbers being variable in length, you could then do something like:
int startpos = s.IndexOf('_', 4);
string newstring = s.Substring(0, startpos - 1) + s.Substring(startpos);
with this code, the following tests resulted in:
"AX_1234X_12345_X_CXY" became "AX_1234_12345_X_CXY"
"AX_123X_12345_X_CXY" became "AX_123_12345_X_CXY"
"AX_234X_12345_X_CXY" became "AX_234_12345_X_CXY"
"AX_1X_12345_X_CXY" became "AX_1_12345_X_CXY"
Something like this could work. I'm sure there's a more elegant solution.
string input1 = "AX_1234X_12345_X_CXY";
string pattern1 = "^[A-Z]{1,2}_[0-9]{1,4}(X)";
string newInput = string.Empty;
Match match = Regex.Match(input1, pattern1);
if(match.Success){
newInput = input1.Remove(match.Groups[1].Index, 1);
}
Console.WriteLine(newInput);

Using Insert when certain length of string is given as input in C#

What I am trying to do is if user input four characters like 0500, I want to add ":" after second character so it becomes 05:00. From trial and error it does't seems to insert correctly.
So part of my codes is
string timeInput = Console.ReadLine();
string[] timeSplit = timeInput.Split(':');
if(timeInput.Length == 4) { // if string = four
timeInput = timeInput.Insert(1, ":");
}
You can't split the string by ':' if your input doesn't contain any ':'. So you don't need the variable timeSplit. You can do it like this:
string timeInput = Console.ReadLine();
if (timeInput.Length == 4) // if input = "0500" -> true
timeInput = timeInput.Insert(2, ":");
Console.WriteLine(timeInput); // Output: 05:00
With timeInput.Insert(1, ":") you would get "0:500" as output.
replace
timeInput = timeInput.Insert(1, ":");
with
timeInput = timeInput.Insert(2, ":");
to insert the : at the second index
string 0 5 0 0
index 0|1|2|3|4
A single character in a string is called a char
Although the length of the string is 4 the indexing starts with 0!
string timeInput = "0500"
When you index it it would look like this:
timeInput[0] -> 0
timeInput[1] -> 5
timeInput[2] -> 0
timeInput[3] -> 0
this is why you need to put the : on position 2
if(timeInput.Length == 4) // if string = four
{
timeInput = timeInput.Insert(2, ":");
}
The first argument of Insert method is the index number where you want to insert any character, after two digit the index number is 2 so It should be 2 instead 1
timeInput = timeInput.Insert(2, ":");
and why do you you spliting the input using : where you haven't inseted : into it? splite after innsert : is the correct one I guess
string timeInput = Console.ReadLine();
if(timeInput.Length == 4)
{ // if string = four
timeInput = timeInput.Insert(2, ":");
}
string[] timeSplit = timeInput.Split(':');

C# split string on X number of alpha numeric values

this might be simple question I have 3 strings
A123949DADWE2ASDASDW
ASDRWE234DS2334234234
ZXC234ASD43D33SDF23SDF
I want to split those by the first 8 characters and then the 10th and 11th and then combine them into one string.
So I would get:
A123949DWE
ASDRWE23S2
ZXC234AS3D
Basically the 9th character and anything after the 12th character is removed.
You can use String.Substring:
s = s.Substring(0, 8) + s[10] + s[11]
Example code:
string[] a = {
"A123949DADWE2ASDASDW",
"ASDRWE234DS2334234234",
"ZXC234ASD43D33SDF23SDF"
};
a = a.Select(s => s.Substring(0, 8) + s[10] + s[11]).ToArray();
Result:
A123949DWE
ASDRWE23S2
ZXC234AS3D
So let's say you have them declared as string variables:
string s1 = "A123949DADWE2ASDASDW";
string s2 = "ASDRWE234DS2334234234";
string s3 = "ZXC234ASD43D33SDF23SDF";
You can use the substring to get what you want:
string s1substring = s1.Substring(0,8) + s1.Substring(9,2);
string s2substring = s1.Substring(0,8) + s1.Substring(9,2);
string s3substring = s1.Substring(0,8) + s1.Substring(9,2);
And that should give you what you need. Just remember, that the string position is zero-based so you'll have to subtract one from the starting position.
So you could do:
string final1 = GetMyString("A123949DADWE2ASDASDW");
string final2 = GetMyString("ASDRWE234DS2334234234");
string final3 = GetMyString("ZXC234ASD43D33SDF23SDF");
public function GetMyString(string Original)
{
string result = Original.Substring(12);
result = result.Remove(9, 1);
return result;
}

Categories

Resources