take only 9 chars after specific word in string [duplicate] - c#

This question already has answers here:
Need to get a string after a "word" in a string in c#
(7 answers)
Closed 4 years ago.
I'm receiving from my app string of numbers, and I need to get them
but I don't know them
so in the string I have UID:
so search it in the string and then I need to take from the string 9 chars after the word "UID:" in the string
tried some and didn't word well
I just removing what I want and not extract it from the string
string id = txt.Substring(0, txt.LastIndexOf("UID:") + 9);
I know the string I need after UID: always have 9 chars
the out put I need to get
EXAMPLE:
UID: 994zxfa6q
I don't know what is it but I know its only have 9 chars.

I prefer not to have constants and length of constants hardcoded separate from each other. You need to have your starting index be the index of the searched string plus the size of the search string, and then your length should be the size of your id.
var uid = "UID: ";
string id = txt.Substring(txt.IndexOf(uid) + uid.Length, 9);

You definitely had the right idea. Almost had it.
string id = txt.Substring(txt.LastIndexOf("UID: ") + 5, 9);

string GetUID(string input)
{
const int uidLength = 9;
const string uidMarker = "UID: ";
var markerIndex = input.IndexOf(uidMarker);
if(markerIndex==-1 || markerIndex + uidMarker.Length + uidLength > input.Length)
{
throw new ArgumentException("Input does not contain UID", nameof(input));
}
return input.Substring(markerIndex + uidMarker.Length, uidLength);
}
If I understand what you want, you can use this code (or something along those lines). Sorry, may have gotten it wrong as I'm far from PC right now. This code assumes that there is only one "UID:" substring in the input string.
Also String.IndexOf and String.Substring are nicely documented.

Your code is almost correct, but you have to remember that the first parameter of string.SubString is an index. So, you need to change:
string id = txt.Substring(0, txt.LastIndexOf("UID:") + 9);
to:
string id = txt.Substring(txt.LastIndexOf("UID:") + 4, 9);

String txt = "UID: 994zxfa6q";
int pFrom = txt.IndexOf("UID:") + 4;
Console.WriteLine("pFrom = " + pFrom.ToString());
int pTo = txt.LastIndexOf("UID:") + 14;
Console.WriteLine("pTo= " + pTo.ToString());
String result = txt.Substring(pFrom, pTo - pFrom);
Console.WriteLine("result " + result);

Related

Out of Range Exception - Substring - C#

I have a list of phone numbers some with extensions, some with out.
I regex my phone number to return just the digits.
I then create a string for the first 10 digits(area code + number).
I compare this strings length and compare it to the original.
If there is a difference, I use the remainder as the extension.
In the code below, I keep getting an out of range exception. I've debugged it, and it does not appear to be out of range. Anyone see what I'm missing?
var prePhone = emp.y.PhoneNumber;
if (!string.IsNullOrEmpty(prePhone))
{
string xPhone = Regex.Replace(prePhone, "[^0-9]", "");
string number = xPhone.Substring(0, 10);
int extMath = xPhone.Length - number.Length;
if (extMath >= 1)
{ int preExt = 9 + extMath;
string ext = xPhone.Substring(10, preExt);//Out of range exception
em.Phone = beautifyPhoneNumber(number, ext);
}
else {
string ext = null;
em.Phone = beautifyPhoneNumber(number, ext);
}
}
string ext = xPhone.Substring(10, preExt)
The second argument is not the ending index, it is the length of the string you want to extract.
Since preExt > 10 in your code, xPhone must be more than 20 characters in length, (since you're starting at index 10), otherwise an exception will be thrown.

Index and length must refer to a location within the string ASP.NET [duplicate]

This question already has answers here:
Index and length must refer to a location within the string
(2 answers)
Closed 8 years ago.
I have method
public static string UrlImageName(string name)
{
if (name.IndexOf("_180x140") <= 0)
{
var extPos = name.LastIndexOf(".");
return name.Substring(0, extPos) + "_180x140" + name.Substring(extPos, name.Length);
}
return name;
}
and view
<div class="car-img">
<img src="#IKWelcomeScreenCellViewModel.UrlImageName(viewModel.SlideShowUrls[0])" />
</div>
names are like this "http://www.ua/Content/images/ik-main-page/Catalog.png"
and I need this http://www.ua/Content/images/ik-main-page/Catalog_180x140.png
error Index and length must refer to a location within the string
I think you are looking for String.Insert
Returns a new string in which a specified string is inserted at a specified index position in this instance.
So simply use
return name.Insert(extPos, "_180x140");
However as per your error is concerned use
return name.Substring(0, extPos) + "_180x140" + name.Substring(extPos);
String.Substring() function takes the startingIndex as first argument and Length/number of characters tobe extracted as second argument.
Replace This:
return name.Substring(0, extPos) + "_180x140" +
name.Substring(extPos, name.Length);
With This:
return name.Substring(0, extPos.Length - extPos) + "_180x140" +
name.Substring(extPos, name.Length - extPos);
Since the second parameter to Substring is a length, this will fail every time unless extPos is 0:
name.Substring(extPos, name.Length);
Change it to this, so that you're only selecting the portion of the string after the period.
name.Substring(extPos + 1, name.Length - extPos - 1);
Or to this, if you want to include the period in the result:
name.Substring(extPos, name.Length - extPos);
You'll probably want an extra check too, if there's a chance there won't be a period in the string.
If extPos is, let's say 5, and the string has 10 characters, then the following line will clip from index 5 to 15, which is out of bounds.
name.Substring(extPos, name.Length);
You should be doing this instead.
name.Substring(extPos, name.Length - extPos);
or, simply,
name.Substring(extPos);
extPos is the position where the extension of the file starts. Now, if you want to insert that _180x140 just before the extension you could use Substring without the length.
This will take the remainder of the string starting from the extPos position and you don't need any calculation to readd the extension
public static string UrlImageName(string name)
{
if (name.IndexOf("_180x140") < 0)
{
var extPos = name.LastIndexOf(".");
return name.Substring(0, extPos) + "_180x140" + name.Substring(extPos);
}
return name;
}

Split a filename in 2 groups

I am making an application which "Filewatches" a folder and when a file is created in there it will automatically be mailed to the customer.
The problem is that i haven't found any information on how to split filenames
For example i have a file called : "Q1040500005.xls"
I need the first 5 characters seperated from the last 5, so basically split it in half (without the extension ofcourse)
And my application has to recognize the "Q1040" and the "500005" as seperate strings.
Which will be recognized in the database which contains The query number (Q1040) and the customer number "500005" the email of the customer and the subject of the queryfile.
How can i do this the easiest way?
Thanks for the help!
Use SubString method http://msdn.microsoft.com/es-es/library/aka44szs(v=vs.80).aspx
int lengthFilename = filename.Length - 4; //substract the string ".xls";
int middleLength = lengthFilename/2;
String filenameA = filename.SubString(0, middleLength);
String filenameB = filename.SubString(middleLength, lengthFilename - middleLength);
Is string.Substring method what you're looking for?
Use String.SubString(int startindex, int length)
String filename = Q1040500005.xls
var queryNumber = filename.Substring(0, 5); //Q1040
var customerNumber = filename.Substring(5, 6); //500005
This assumes your strings are a constant length.
Hope this helps.
You can use string.SubString() here
string a = fileName.SubString(0, 5); // "Q1040"
string b = fileName.SubString(5, 5); // "50000" <- Are you sure you didn't mean "last 6"?
string b2 = fileName.SubString(5, 6); // "500005"
This only works, if both strings have a constant fixed length
Edit:
If on the other hand, both strings can have variable length, I'd recommend you use a separator to divide them ("Q1040-500005.xml"), then use string.Split()
string[] separatedStrings = fileName.Split(new char[] { '-', '.' });
string a = separated[0]; // "Q1040"
string b = separated[1]; // "500005"
string extension = separated[2]; // "xls"

get all characters to right of last dash

I have the following:
string test = "9586-202-10072"
How would I get all characters to the right of the final - so 10072. The number of characters is always different to the right of the last dash.
How can this be done?
You can get the position of the last - with str.LastIndexOf('-'). So the next step is obvious:
var result = str.Substring(str.LastIndexOf('-') + 1);
Correction:
As Brian states below, using this on a string with no dashes will result in the original string being returned.
You could use LINQ, and save yourself the explicit parsing:
string test = "9586-202-10072";
string lastFragment = test.Split('-').Last();
Console.WriteLine(lastFragment);
I can see this post was viewed over 46,000 times. I would bet many of the 46,000 viewers are asking this question simply because they just want the file name... and these answers can be a rabbit hole if you cannot make your substring verbatim using the at sign.
If you simply want to get the file name, then there is a simple answer which should be mentioned here. Even if it's not the precise answer to the question.
result = Path.GetFileName(fileName);
see https://msdn.microsoft.com/en-us/library/system.io.path.getfilename(v=vs.110).aspx
string tail = test.Substring(test.LastIndexOf('-') + 1);
YourString.Substring(YourString.LastIndexOf("-"));
With the latest C# 8 and later you can use Range Indexer as follows:-
string test = "9586-202-10072"
var foo = test?[(test.LastIndexOf('-') + 1)..];
// foo is => 10072
string atest = "9586-202-10072";
int indexOfHyphen = atest.LastIndexOf("-");
if (indexOfHyphen >= 0)
{
string contentAfterLastHyphen = atest.Substring(indexOfHyphen + 1);
Console.WriteLine(contentAfterLastHyphen );
}
See String.lastIndexOf method
I created a string extension for this, hope it helps.
public static string GetStringAfterChar(this string value, char substring)
{
if (!string.IsNullOrWhiteSpace(value))
{
var index = value.LastIndexOf(substring);
return index > 0 ? value.Substring(index + 1) : value;
}
return string.Empty;
}
test.Substring[(test.LastIndexOf('-') + 1)..]
C# 8 (late 2019) introduces range operator and simplifies it a bit further. The two dots here means from the index (inclusive) till the end of string.
test.Substring(test.LastIndexOf("-"))
and... in case you need the left part of a string:
private string AllTheLeftPart(string theString)
{
string rightPart = theString.Substring(theString.LastIndexOf('-') + 1);
string leftPart theString.Replace("-" + rightPart, String.Empty);
return leftPart ;
}

how to place - in a string

I have a string "8329874566".
I want to place - in the string like this "832-98-4566"
Which string function can I use?
I would have done something like this..
string value = "8329874566";
value = value.Insert(6, "-").Insert(3, "-");
You convert it to a number and then format the string.
What I like most about this is it's easier to read/understand what's going on then using a few substring methods.
string str = "832984566";
string val = long.Parse(str).ToString("###-##-####");
There may be a tricky-almost-unreadable regex solution, but this one is pretty readable, and easy.
The first parameter of the .Substring() method is where you start getting the characters, and the second is the number of characters you want to get, and not giving it sets a default as value.length -1 (get chars until the end of the string):
String value = "8329874566";
String Result = value.Substring(0,3) + "-" + value.Substring(3,2) + "-" + value.Substring(6);
--[edit]--
Just noticed you didn't use one of the numbers AT ALL (number '7') in the expected result example you gave, but if you want it, just change the last substring as "5", and if you want the '7' but don't want 5 numbers in the last set, let it like "5,4".
Are you trying to do this like American Social Security numbers? I.e., with a hyphen after the third and and fifth numerals? If so:
string s = "8329874566";
string t = String.Format("{0}-{1}-{2}", s.Substring(0, 3), s.Substring(3, 2), s.Substring(5));
Just out of completeness, a regular expression variant:
Regex.Replace(s, #"(\d{3})(\d{2})(\d{4})", "$1-$2-$3");
I consider the Insert variant to be the cleanest, though.
This works fine, and I think that is more clear:
String value = "8329874566";
value = value.Insert(3, "-").Insert(6, "-");
The console outputs shows this:
832-98-74566
If the hyphens are to go in the same place each time, then you could simply concatenate together the pieces of the orginal string like this:
// 0123456789 <- index
string number = "8329874566";
string new = number.Substring(0, 3) + "-" + number.Substring(3, 2) + "-" + number.Substring(5);
For a general way of making mutable strings, use the StringBuilder class. This allows deletions and insertions to be made before calling ToString to produce the final string.
You could try the following:
string strNumber = "8329874566"
string strNewNumber = strNumber.Substring(0,3) + "-" + strNumber.Substring(4,2) + "-" strNumber.Substring(6)
or something in this manner
string val = "832984566";
string result = String.Format("{0}-{1}-{2}", val.Substring(0,3), val.Substring(3,2), val.Substring(5,4));
var result = string.Concat(value.Substring(0,3), "-", value.Substring(3,2), "-", value.Substring(5,4));
or
var value = "8329874566".Insert(3, "-").Insert(6, "-");
Now how about this for a general solution?
// uglified code to fit within horizontal limits
public static string InsertAtIndices
(this string original, string insertion, params int[] insertionPoints) {
var mutable = new StringBuilder(original);
var validInsertionPoints = insertionPoints
.Distinct()
.Where(i => i >= 0 && i < original.Length)
.OrderByDescending(i => i);
foreach (int insertionPoint in validInsertionPoints)
mutable.Insert(insertionPoint, insertion);
return mutable.ToString();
}
Usage:
string ssn = "832984566".InsertAtIndices("-", 3, 5);
string crazy = "42387542342309856340924803"
.InsertAtIndices(":", 1, 2, 3, 4, 5, 6, 17, 200, -1, -1, 2, 3, 3, 4);
Console.WriteLine(ssn);
Console.WriteLine(crazy);
Output:
832-98-4566
4:2:3:8:7:5:42342309856:340924803
Overkill? Yeah, maybe...
P.S. Yes, I am regex illiterate--something I hope to rectify someday.
A straightforward (but not flexible) approach would be looping over the characters of the string while keeping a counter running. You can then construct a new string character by character. You can add the '-' character after the 3rd and 5th character.
A better approach may be to use a function to insert a single character in the middle of the string at a specific index. String.Insert() would do well. The only thing to pay attention to here is that the string indexes will get off by one with each insert.
EDIT more language-specific as per comments

Categories