Today I'm trying to fix some problem but i can't understand why return this Ans to me.
string text = "<Design><Code>"
var Ans = text.Substring(0, text.IndexOf(">"));
I can't understand why Ans will return "<Design" this to me.
I think the "<Design>" <-- this Ans was correct.
The problem is that IndexOf is going to return the zero-based index. text.Substring() is wanting the length as an argument, or the one-based number of characters in the string.
If I index, starting at zero, under your input:
<Design><Code>
01234567
You're passing 7 as the number of characters. If I count (starting at ONE) under your input:
<Design><Code>
1234567
You can see that the first seven characters are <Design
Related
I am attempting convert this string "123456" to "12-34-56".
I try to use this code but it doesn't seem to work correctly
string.Format("00-00-00", "123456");
Can anyone help me find a suitable pattern? Thanks for any help
Your format string is not correct, composite formatted string should be enclosed within curly braces and can have three parameters as follows,
{ index[,alignment][:formatString] }
While alignment and formatString are optional, index is mandatory.
In your case, it is a single string "123456" with index 0 which is to be formatted in the following pattern "12-34-56".
So, we use the index and format string to achieve the desired output.
To represent a digit 0-9 (optional) in the format string, we use the placeholder '#'.
'#' holds 0, if there exists no digit corresponding to the position in the object, else it replaces the 0 with the digit in place.
The following format string would be suitable for your need,
##-##-## -> three numbers with 2 digits each separated by a hyphen.
Now, putting that in place using the composite format syntax,
"{0:##-##-##}"
Usage:
String input:
var s = "123456";
Console.WriteLine("{0:##-##-##}", Convert.ToInt32(s));
Integer input:
var n = 123456;
Console.WriteLine("{0:##-##-##}", n);
Use below
string.Format("{0:##-##-##}", 123456);
If number is represented as string the convert to int
string.Format("{0:##-##-##}", Convert.ToInt32("123456"));
The above will print the output as
12-34-56
This question already has answers here:
How to get the last five characters of a string using Substring() in C#?
(12 answers)
Closed 4 years ago.
If a string that contains integers and I want to split it based on integers occurrence. how to do that?
string test= "a b cdf 7654321;
then I want to store the integer and all words before it, like this
string stringBefore="";
// the integer will be last item
string integer="";
Note:
in my case the integer always will be 7 digits
You can use Regex.Split with a capture group to return the delimiter:
var ans = Regex.Split(test, #"("\d{7})");
If the number is at the end of the string, this will return an extra empty string. If you know it is always at the end of the string, you can split on its occurrence:
var ans = Regex.Split(test, #"(?=\d{7})");
According to your comments the integer is always 7 digits and it is always the last item of the string.
In that case, just use Substring()
string test = "a b cdf 7654321";
string stringBefore = test.Substring(0, test.Length - 7);
string integer = test.Substring(test.Length - 7);
Substring just makes a string based on a portion of your original string.
EDIT
I was a little surprised to find there wasn't a built in way to easily split a string in to two strings based on an index (maybe I missed it). I came up with a LINQ extension method that achieves what I was trying to do, maybe you will find it useful:
public static string[] SplitString(this string input, int index)
{
if(index < 0 || input.Length < index)
throw new IndexOutOfRangeException();
return new string[]
{
String.Concat(input.Take(input.Length - index)),
String.Concat(input.Skip(input.Length - index))
};
}
I think I would rather use a ValueTuple if using C# 7, but string array would work too.
Fiddle for everything here
i am trying to learn programming by doing some simple exercises online.
and after searching i couldn't find a answer.
Problem:
public static void Main(string[] args)
{
// get sentence
Console.WriteLine("type a sentence: ");
string Sentence = Console.ReadLine();
// insert code for cutting sentence in half
// display first half of the sentence
Console.Write(firstHalf);
Console.WriteLine();
}
}
thanks in advance !
You can use the String.Substring method for that.
string firsthalf = Sentence.Substring(0, Sentence.Length/2);
The first parameter 0 is the starting point of the substring and the second denotes how many characters the substring should include.
The String.Length property helps you to determine the length of the string.
Important note:
When you divide the length by 2 you need to know that it is an integer division! That means that 3/2 = 1 and 1/2 = 0 so if your string is only 1 character long you will be an empty string as the first half ;) and if it is 3 letters long you get only the first letter.
Good fortune with the learning :)
You can get the length of the string using the Length property and use Substring to take half of the string
firstHalf = s.Substring(0, s.Length / 2)
You can use the range operator ..:
var firstHalf = sentence[..(sentence.Length / 2)];
source
You can use Remove:
var firstHalf = sentence.Remove(sentence.Length/2);
I want to remove last three characters from a string:
string myString = "abcdxxx";
Note that the string is dynamic data.
read last 3 characters from string [Initially asked question]
You can use string.Substring and give it the starting index and it will get the substring starting from given index till end.
myString.Substring(myString.Length-3)
Retrieves a substring from this instance. The substring starts at a
specified character position. MSDN
Edit, for updated post
Remove last 3 characters from string [Updated question]
To remove the last three characters from the string you can use string.Substring(Int32, Int32) and give it the starting index 0 and end index three less than the string length. It will get the substring before last three characters.
myString = myString.Substring(0, myString.Length-3);
String.Substring Method (Int32, Int32)
Retrieves a substring from this instance. The substring starts at a
specified character position and has a specified length.
You can also using String.Remove(Int32) method to remove the last three characters by passing start index as length - 3, it will remove from this point to end of string.
myString = myString.Remove(myString.Length-3)
String.Remove Method (Int32)
Returns a new string in which all the characters in the current
instance, beginning at a specified position and continuing through the
last position, have been deleted
myString = myString.Remove(myString.Length - 3, 3);
I read through all these, but wanted something a bit more elegant. Just to remove a certain number of characters from the end of a string:
string.Concat("hello".Reverse().Skip(3).Reverse());
output:
"he"
The new C# 8.0 range operator can be a great shortcut to achieve this.
Example #1 (to answer the question):
string myString = "abcdxxx";
var shortenedString = myString[0..^3]
System.Console.WriteLine(shortenedString);
// Results: abcd
Example #2 (to show you how awesome range operators are):
string s = "FooBar99";
// If the last 2 characters of the string are 99 then change to 98
s = s[^2..] == "99" ? s[0..^2] + "98" : s;
System.Console.WriteLine(s);
// Results: FooBar98
myString.Remove(myString.Length-3);
string test = "abcdxxx";
test = test.Remove(test.Length - 3);
//output : abcd
You can use String.Remove to delete from a specified position to the end of the string.
myString = myString.Remove(myString.Length - 3);
Probably not exactly what you're looking for since you say it's "dynamic data" but given your example string, this also works:
? "abcdxxx".TrimEnd('x');
"abc"
If you're working in C# 8 or later, you can use "ranges":
string myString = "abcdxxx";
string trimmed = myString[..^3]; // "abcd"
More examples:
string test = "0123456789", s;
char c;
c = test[^3]; // '7'
s = test[0..^3]; // "0123456"
s = test[..^3]; // "0123456"
s = test[2..^3]; // "23456"
s = test[2..7]; // "23456"
//c = test[^12]; // IndexOutOfRangeException
//s = test[8..^3]; // ArgumentOutOfRangeException
s = test[7..^3]; // string.Empty
str= str.Remove(str.Length - 3);
myString.Substring(myString.Length - 3, 3)
Here are examples on substring.>>
http://www.dotnetperls.com/substring
Refer those.
string myString = "abcdxxx";
if (myString.Length<3)
return;
string newString=myString.Remove(myString.Length - 3, 3);
Easy. text = text.remove(text.length - 3). I subtracted 3 because the Remove function removes all items from that index to the end of the string which is text.length. So if I subtract 3 then I get the string with 3 characters removed from it.
You can generalize this to removing a characters from the end of the string, like this:
text = text.remove(text.length - a)
So what I did was the same logic. The remove function removes all items from its inside to the end of the string which is the length of the text. So if I subtract a from the length of the string that will give me the string with a characters removed.
So it doesn't just work for 3, it works for all positive integers, except if the length of the string is less than or equal to a, in that case it will return a negative number or 0.
Remove the last characters from a string
TXTB_DateofReiumbursement.Text = (gvFinance.SelectedRow.FindControl("lblDate_of_Reimbursement") as Label).Text.Remove(10)
.Text.Remove(10)// used to remove text starting from index 10 to end
items.Remove(items.Length - 3)
string.Remove() removes all items from that index to the end. items.length - 3 gets the index 3 chars from the end
You can call the Remove method and pass the last 3 characters
str.Substring(str.Length-3)
Complete code can be
str.Remove(str.Substring(str.Length-3));
Basically I have some filenames where there is a year in the middle. I am only interested in getting any letter or number up until the year value, but only letters and numbers, not commas, dots, underscores, etc. Is it possible? Maybe with Regex?
For instance:
"A-Good-Life-2010-For-Archive"
"Any.Chararacter_Can+Come.Before!2011-RedundantInfo"
"WhatyouseeIsWhatUget.2012-Not"
"400-Gestures.In1.2000-Communication"
where I want:
"AGoodLife"
"AnyChararacterCanComeBefore"
"WhatyouseeIsWhatUget"
"400GesturesIn1"
By numbers I mean any number that doesn't look like a year, i.e. 1 digit, 2 digits, 3 digits, 5 digits, and so on. I only want to recognize 4 digit numbers as years.
You'll have to do this in two parts -- first to remove the symbols you don't want, and second to grab everything up to the year (or vice versa).
To do grab everything up to the year, you can use:
Match match = Regex.Match(movieTitle,#"(.*)(?<!\d)(?:19|20)[0-9]{2}(?!\d)");
// if match.Success, result is in match.Groups[1].value
I've made the year regex so it only matches things in the 1900s or 2000s, to make sure you don't match four-digit numbers as year if they're not a year (e.g. "Ali-Baba-And-the-1234-Thieves.2011").
However, if your movie title involves a year, then this won't really work ("2001:-Space-Odyssey(1968)").
To then replace all the non-characters, you can replace "[^a-zA-Z0-9]" with "". (I've allowed digits because a movie might have legitimate numbers in the title).
UPDATED from comments below:
if you search from the end to find the year you might do better. ie find the latest occuring year-candidate as the year. Hence, I've changed a .*? to .* in the regex so that the title is as greedy as possible and only uses the last year-candidate as the year.
Added a (?!\d) to the end of the year regex and a (?<!\d) to the start so that it doesn't match "My-title-1" instead of "My-title-120012-fdsa" & "2001" in "My-title-120012-fdsa" (I didn't add the boundary \b because the title might be "A-Good-Life2010" which has no boundary around the year).
changed the string to a raw string (#"...") so I don't need to worry about escaping backslashes in the regex because of C# interpreting backslashes.
you can try like this
/\b\d{4}\b/
d{4}\b will match four d's at a word boundary.Depending on the input data you may also want to consider adding another word boundary (\b) at the beginning.
using System.Text.RegularExpressions;
string GoodParts(string input) {
Regex re = new Regex(#"^(.*\D)\d{4}(\D|$)");
var match = re.Match(input);
string result = Regex.Replace(match.Groups[1].Value, "[^0-9a-zA-Z]+", "");
return result;
}
You can use Regex.Split() to make the code ever so terser (and possibly faster due to the simpler regex):
var str = "400-Gestures.In1.2000-Communication";
var re = new Regex(#"(^|\D)\d{4}(\D|$)");
var start = re.Split(str)[0];
// remove nonalphanumerics
var result = new string(start.Where(c=>Char.IsLetterOrDigit(c)).ToArray());
I suppose you want a fancy regular excpression?
Why not a simple for loop?
digitCount = 0;
for i = 0 to strlen(filename)
{
if isdigit(fielname[i])
{
digitCount++;
if digitCount == 4
thePartOfTheFileNameThatYouWant = strcpy(filename, 0, i-4)
}
else digitCount = 0;
}
// Sorry, I don't know C-sharp