I have an input string. I need to replace its prefix (until first dot) with an other string.
The method signature:
string MyPrefixReplace(string input, string replacer)
Examples:
string res = MyPrefixReplace("12.345.6789", "000")
res = "000.345.6789";
res = MyPrefixReplace("908.345.6789", "1")
res = "1.345.6789";
Is there a way not to extract a sub-string before first dot and make a Replace**?
I.e - I don't want this solution
int i = input.IndexOf(".");
string rep = input.Substring(0,i);
input.Replace(rep,replacer);
Thanks
You could use String.Split
public string MyPrefixReplace(string source, string value, char delimiter = '.')
{
var parts = source.Split(delimiter);
parts[0] = value;
return String.Join(delimiter.ToString(), parts);
}
Live demo
Using String.IndexOf and String.Substring ist the most efficient way. In your approach you have used the wrong overload of Substring. String.Replace is pointless anyway since you don't want to replace all occurences of the first part but only the first part.
Therefore you don't have to take but to skip the the first part and prefix another. This works as desired:
public static string MyPrefixReplace(string input, string replacer, char prefixChar = '.')
{
int index = input.IndexOf(prefixChar);
if (index == -1)
return input;
return replacer + input.Substring(index);
}
Your input:
string result = MyPrefixReplace("908.345.6789", "1"); // 1.345.6789
result = MyPrefixReplace("12.345.6789", "000"); // 000.345.6789
Personally, I'd split the string up to get around this problem, although there's obviously other ways of doing this, this would be my approach:
string Input = "123.456.789"
string[] SplitInput = Input.Split('.');
SplitInput[0] = "321";
string Output = String.Join('.', SplitInput);
Output should be "321.456.789".
Related
I have a string which has two tokens that bound a substring that I want to extract, but the substring may contain the tokens themselves, so I want between the 1st occurrence of token A and the last occurrence of token B. I also need to search for the tokens in a case-insensitive search.
Tried to wrap my head around using regex to get this, but can't seem to figure it out. Not sure the best approach here. String.split won't work.
I can't modify the casing of the data between the tokens in the string.
Try this, (I've made it into an extension method)
public static string Between(this string value, string a, string b)
{
int posA = value.IndexOf(a);
int posB = value.LastIndexOf(b);
if (posA == -1) || (posB == -1)
{
return "";
}
int adjustedPosA = posA + a.Length;
return (adjustedPosA >= posB) ? "" : value.Substring(adjustedPosA, posB - adjustedPosA);
}
Usage would be:
var myString = "hereIsAToken_andThisIsWhatIwant_andSomeOtherToken";
var whatINeed = myString.Between("hereIsAToken_", "_andSomeOtherToken");
An easy way to approach this problem is the use of the indexOf function provided by the string class. IndexOf returns the first occurence, lastIndexOf as the name suggests, the last one.
string data;
string token1;
string token2;
int start = data.IndexOf(token1)+token1.Length;
int end = data.LastIndexOf(token2);
string result = data.Substring(start, end-start);
From my personal point of view, regex might be a bit overkill here, just try my example :)
I'm trying to compare first 3 chars of a string, i'm trying to use substring then compare.
The strings are read from an input file, and the string may not be 3 chars long. if an string is not 3 chars long i want the substring method to replace the empty chars with spaces.
How would i go about doing that.
Current code throws an exeption when the string is not long enough.
Use String.PadRight
myString.PadRight(3, ' ');
// do SubString here..
You could also create a .Left extension method that doesn't throw an exception when the string isn't big enough:
public static string Left(this string s, int len)
{
if (len == 0 || s.Length == 0)
return "";
else if (s.Length <= len)
return s;
else
return s.Substring(0, len);
}
Usage:
myString.Left(3);
Use one of the String.PadRight() methods before calling Substring():
string subString = myString.PadRight(3).Substring(0,3);
If you use the overload with one parameter like I did above, it will insert spaces.
string subString1 = string1.PadRight(3).Substring(0,3);
string subString2 = string2.PadRight(3).Substring(0,3);
if (String.Compare(subString1, subString2) == 0)
{
// if equal
}
else
{
// not equal
}
I used separate variables because it's a bit more readable, but you could in-line them in the if statement if you wanted to.
You can use this dirty hack:
var res = (myStr+" ").Substring(...);
Ill lose to much time since i don`t have too much experience in manipulating with strings/chars.
i have
string original = "1111,2222,"This is test work")";
i need
string first = "1111";
string second = "2222";
string name = "This is test work";
C# ASP.NET
Use string.Split() - your pattern is simple (split on comma), there is no need to use a RegEx here:
var parts = original.Split(',');
first = parts[0];
second = parts[1];
name = parts[2].TrimEnd(')'); //in case you really wanted to remove that last bracket
Use the String.Split method:
string[] values = original.Split(new Char [] {','});
This will break apart your string at every comma and return a string array containing each part. To access:
string first = values[0];
string second = values[1];
string name = values[2];
I have strings that look like this:
1. abc
2. def
88. ghi
I'd like to be able to get the numbers from the strings and put it into a variable and then get the remainder of the string and put it into another variable. The number is always at the start of the string and there is a period following the number. Is there an easy way that I can parse the one string into a number and a string?
May not be the best way, but, split by the ". " (thank you Kirk)
everything afterwards is a string, and everything before will be a number.
You can call IndexOf and Substring:
int dot = str.IndexOf(".");
int num = int.Parse(str.Remove(dot).Trim());
string rest = str.Substring(dot).Trim();
var input = "1. abc";
var match = Regex.Match(input, #"(?<Number>\d+)\. (?<Text>.*)");
var number = int.Parse(match.Groups["Number"].Value);
var text = match.Groups["Text"].Value;
This should work:
public void Parse(string input)
{
string[] parts = input.Split('.');
int number = int.Parse(parts[0]); // convert the number to int
string str = parts[1].Trim(); // remove extra whitespace around the remaining string
}
The first line will split the string into an array of strings where the first element will be the number and the second will be the remainder of the string.
Then you can convert the number into an integer with int.Parse.
public Tuple<int, string> SplitItem(string item)
{
var parts = item.Split(new[] { '.' });
return Tuple.Create(int.Parse(parts[0]), parts[1].Trim());
}
var tokens = SplitItem("1. abc");
int number = tokens.Item1; // 1
string str = tokens.Item2; // "abc"
I have some strings like below:
string num1 = "D123_1";
string num2 = "D123_2";
string num3 = "D456_11";
string num4 = "D456_22";
string num5 = "D_123_D";
string num5 = "_D_123";
I want to make a function that will do the following actions:
1- Checks if given string DOES HAVE an Underscore in it, and this underscore should be after some Numbers and Follow with some numbers: in this case 'num5' and 'num6' are invalid!
2- Replace the numbers after the last underscore with any desired string, for example I want 'num1 = "D123_1"' to be changed into 'D123_2'
So far I came with this idea but it is not working :( First I dont know how to check for criteria 1 and second the replace statement is not working:
private string CheckAndReplace(string given, string toAdd)
{
var changedString = given.Split('_');
return changedString[changedString.Length - 1] + toAdd;
}
Any help and tips will be appriciated
What you are looking for is a regular expression. This is (mostly) from the top of my head. But it should easily point you in the right direction. The regular expression works fine.
public static Regex regex = new Regex("(?<character>[a-zA-Z]+)(?<major>\\d+)_(?<minor>\\d+)",RegexOptions.CultureInvariant | RegexOptions.Compiled);
Match m = regex.Match(InputText);
if (m.Succes)
{
var newValue = String.Format("{0}{1}_{2}"m.Groups["character"].Value, m.Groups["major"].Value, m.Groups["minor"].Value);
}
In your code you split the String into an array of strings and then access the wrong index of the array, so it isn't doing what you want.
Try working with a substring instead. Find the index of the last '_' and then get the substring:
private string CheckAndReplace(string given, string toAdd) {
int index = given.LastIndexOf('_')+1;
return given.Substring(0,index) + toAdd;
}
But before that check the validity of the string (see other answers). This code fragment will break when there's no '_' in the string.
You could use a regular expression (this is not a complete implementation, only a hint):
private string CheckAndReplace(string given, string toAdd)
{
Regex regex = new Regex("([A-Z]*[0-9]+_)[0-9]+");
if (regex.IsMatch(given))
{
return string.Concat(regex.Match(given).Groups[1].Value, toAdd);
}
else
{
... do something else
}
}
Use a good regular expression implementation. .NET has standard implementation of them