String concatenation based on best practices - c#

I have a string,
string ij = "/alwaysSame09102012/myThing.aspx?asdasd=99&Urasdl=scashdasdeasdmeasds/tasdigaesdr1/gasdoasdveasdasdrnaasdancasde/eamsdeasdetiasdasdnagsds/tasidgeasdr1masdeetasdasd11180,/reasdMeasdetMe2as0d1asd0/asrdganasdiseasdasdgeasdetasdiasdngaasdsd.aasdspafsxasdffas?asdsdlaieasdnedtfe=asdsafaser1meafswedfhfdget111ertert80"
Now i just need to change the first "alwaysSame09102012" with "always2013forever".
I know i can do something like this,
string ij = "/alwaysSame09102012/myThing.aspx?asdasd=99&Urasdl=scashdasdeasdmeasds/tasdigaesdr1/gasdoasdveasdasdrnaasdancasde/eamsdeasdetiasdasdnagsds/tasidgeasdr1masdeetasdasd11180,/reasdMeasdetMe2as0d1asd0/asrdganasdiseasdasdgeasdetasdiasdngaasdsd.aasdspafsxasdffas?asdsdlaieasdnedtfe=asdsafaser1meafswedfhfdget111ertert80"
string[] c = ij.split['/'];
string finalString = ij.replace( "/" + c[0] + "/", "/" + "always2013forever" + "/");
This is my logic but no working, please help,
only constant in my string is "/alwaysSame09102012/" which i need to replace
Update
**
What if I got this "alwaysSame09102012" in at of my query string,
that's why I don't want to use replace.
**

Use String.Replace.
Ex:
var goodStr = ij.Replace("alwaysSame09102012", "always2013forever");
The reason your answer does not work is because c[0] is going to be "". The value you are looking for (e.g. 'alwaysSame09102012') is going to be in c[1].

string ij = "/alwaysSame09102012/myThing.aspx?asdasd=99&Urasdl=scashdasdeasdmeasds/tasdigaesdr1/gasdoasdveasdasdrnaasdancasde/eamsdeasdetiasdasdnagsds/tasidgeasdr1masdeetasdasd11180,/reasdMeasdetMe2as0d1asd0/asrdganasdiseasdasdgeasdetasdiasdngaasdsd.aasdspafsxasdffas?asdsdlaieasdnedtfe=asdsafaser1meafswedfhfdget111ertert80"
string newString = ij.Replace("alwaysSame09102012","always2013forever");

string ReplaceFirst (string source, string old_substring, string new_substring)
{
var position = source.IndexOf(old_substring);
return (position < 0)
? source
: source.Substring(0, position) + new_substring + source.Substring(position + old_substring.Length);
}
Usage:
var new_string = ReplaceFirst("/alwaysSame09102012/myThing...", "alwaysSame09102012","always2013forever");

You should use the URI classes.
http://msdn.microsoft.com/en-us/library/system.uri.aspx
http://msdn.microsoft.com/en-us/library/system.uribuilder.aspx
This will give you more flexibility, and prevent you from escaping problems etc.

Related

Remove characters in string?

Here is my string:
[{"url":"http:\/\/is1.mzstatic.com\/image\/thumb\/Music6\/v4\/47\/20\/1f\/47201fb7-ddbf-2ff9-767d-4e26065d0158\/source\/600x600bb.jpg"
Here is what I need:
http:\/\/is1.mzstatic.com\/image\/thumb\/Music6\/v4\/47\/20\/1f\/47201fb7-ddbf-2ff9-767d-4e26065d0158\/source\/600x600bb.jpg
I am positive I use the following to remove the quotation marks:
s = s.Replace("\"", "");
But how would I remove:
[{"url":
I think I would use something like:
int index = sourceString.IndexOf(removeString);
string cleanPath = (index < 0)
? sourceString
: sourceString.Remove(index, removeString.Length);
but for some reason I cannot add it to here due to it itself using double quotes.
Assuming you aren't using any JSON libraries and just getting the property url value then why not keep it simple with string.IndexOf() and ignore the first and last char?
var idx = rawJSON.IndexOf(':');
if ( idx > -1 )
{
return rawJSON.SubString(idx + 2, rawJSON.Length - (idx + 2 + 1)); //calculating in my head....
}
else
{
return rawJSON;
}
This works a treat:
var s = #"[{""url"":""http:\/\/is1.mzstatic.com\/image\/thumb\/Music6\/v4\/47\/20\/1f\/47201fb7-ddbf-2ff9-767d-4e26065d0158\/source\/600x600bb.jpg""}]";
var jarray = Newtonsoft.Json.JsonConvert.DeserializeObject(s) as Newtonsoft.Json.Linq.JArray;
var url = jarray[0].Value<string>("url");
I get:
http://is1.mzstatic.com/image/thumb/Music6/v4/47/20/1f/47201fb7-ddbf-2ff9-767d-4e26065d0158/source/600x600bb.jpg
You just need to NuGet "Newtonsoft.Json" to get the library in.
You can use Replace() again on your [{"url":, just remember that you removed the " on the first Replace, so it is now only [{url:
s = s.Replace("\"","");
s = s.Replace("[{url:", ""); // s no longer has " after the first Replace

Remove trailing pipes - '|' in c#

I have a string that looks something like this:
"PID||000000|Z123345|23345|SOMEONE^FIRSTNAME^^^MISS^||150|F|1111||1 DREYFUS CLOSE^SOUTH CITY^COUNTY^^POST CODE^^^||0123 45678910^PRN^PH^^^^0123 45678910^^~^^CP^^^^^^~^NET^^^^^^^||||1A|||||A||||||||N||||||||||";
I am trying to remove any separating '|' characters after the 30th '|' in the string so that the output string looks like this:
"PID||000000|Z123345|23345|SOMEONE^FIRSTNAME^^^MISS^||150|F|1111||1 DREYFUS CLOSE^SOUTH CITY^COUNTY^^POST CODE^^^||0123 45678910^PRN^PH^^^^0123 45678910^^~^^CP^^^^^^~^NET^^^^^^^||||1A|||||A||||||||N";
I am trying to do it using as little code as possible, but not having much luck. Any help or ideas would be great.
You can use the TrimEnd method
string text = "stuff||||N||||||||||";
string result = text.TrimEnd('|'); //Result is stuff||||N
Brute force but only a little bit of code:
string s2 = string.Join("|", s1.Split('|').Take(31));
If you need any other processing of this kind of data (it looks like a kind of nested CSV) then string.Split() is useful to know.
string str = "PID||000000|Z123345|23345|SOMEONE^FIRSTNAME^^^MISS^||150|F|1111||1 DREYFUS CLOSE^SOUTH CITY^COUNTY^^POST CODE^^^||0123 45678910^PRN^PH^^^^0123 45678910^^~^^CP^^^^^^~^NET^^^^^^^||||1A|||||A||||||||N||||||||||";
int c = 0;
int after = 30;
StringBuilder newStr = new StringBuilder();
for(int i = 0;i < str.length; i++){
if(str[i] == '|'){
if(after != c){
newStr.append(str[i]);
c++;
}
}else{
newStr.append(str[i]);
}
}
results in
newStr == "PID||000000|Z123345|23345|SOMEONE^FIRSTNAME^^^MISS^||150|F|1111||1 DREYFUS CLOSE^SOUTH CITY^COUNTY^^POST CODE^^^||0123 45678910^PRN^PH^^^^0123 45678910^^~^^CP^^^^^^~^NET^^^^^^^||||1A|||||A||||||||N";
A regex should do the trick:
var regex = new Regex(#"^([^\|]*\|){0,30}[^\|]*");
var match = regex.Match(input);
if(match.Success)
{
var val = match.Value;
}
If what you really want is that everything after the 30th chunk loses its '|', then try:
var chunks = input.Split('|');
var output = String.Join('|',chunks.Take(30)) + String.Concat(chunks.Skip(30));
That said, I think it sounds like what you're really looking for is probably something like:
var output = input.TrimEnd('|');
// Get the indexes of all the | characters.
int[] pipeIndexes = Enumerable.Range(0, s.Length).Where(i => s[i] == '|').ToArray();
// If there are more than thirty pipes:
if (pipeIndexes.Length > 30)
{
// The former part of the string remains intact.
string formerPart = s.Substring(0, pipeIndexes[30]);
// The latter part needs to have all | characters removed.
string latterPart = s.Substring(pipeIndexes[30]).Replace("|", "");
s = formerPart + latterPart;
}

formatting string in MVC /C#

I have a string 731478718861993983 and I want to get this 73-1478-7188-6199-3983 using C#. How can I format it like this ?
Thanks.
By using regex:
public static string FormatTest1(string num)
{
string formatPattern = #"(\d{2})(\d{4})(\d{4})(\d{4})(\d{4})";
return Regex.Replace(num, formatPattern, "$1-$2-$3-$4-$5");
}
// test
string test = FormatTest1("731478718861993983");
// test result: 73-1478-7188-6199-3983
If you're dealing with a long number, you can use a NumberFormatInfo to format it:
First, define your NumberFormatInfo (you may want additional parameters, these are the basic 3):
NumberFormatInfo format = new NumberFormatInfo();
format.NumberGroupSeparator = "-";
format.NumberGroupSizes = new[] { 4 };
format.NumberDecimalDigits = 0;
Next, you can use it on your numbers:
long number = 731478718861993983;
string formatted = number.ToString("n", format);
Console.WriteLine(formatted);
After all, .Net has very good globalization support - you're better served using it!
string s = "731478718861993983"
var newString = (string.Format("{0:##-####-####-####-####}", Convert.ToInt64(s));
LINQ-only one-liner:
var str = "731478718861993983";
var result =
new string(
str.ToCharArray().
Reverse(). // So that it will go over string right-to-left
Select((c, i) => new { #char = c, group = i / 4}). // Keep group number
Reverse(). // Restore original order
GroupBy(t => t.group). // Now do the actual grouping
Aggregate("", (s, grouping) => "-" + new string(
grouping.
Select(gr => gr.#char).
ToArray())).
ToArray()).
Trim('-');
This can handle strings of arbitrary lenghs.
Simple (and naive) extension method :
class Program
{
static void Main(string[] args)
{
Console.WriteLine("731478718861993983".InsertChar("-", 4));
}
}
static class Ext
{
public static string InsertChar(this string str, string c, int i)
{
for (int j = str.Length - i; j >= 0; j -= i)
{
str = str.Insert(j, c);
}
return str;
}
}
If you're dealing strictly with a string, you can make a simple Regex.Replace, to capture each group of 4 digits:
string str = "731478718861993983";
str = Regex.Replace(str, "(?!^).{4}", "-$0" ,RegexOptions.RightToLeft);
Console.WriteLine(str);
Note the use of RegexOptions.RightToLeft, to start capturing from the right (so "12345" will be replaced to 1-2345, and not -12345), and the use of (?!^) to avoid adding a dash in the beginning.
You may want to capture only digits - a possible pattern then may be #"\B\d{4}".
string myString = 731478718861993983;
myString.Insert(2,"-");
myString.Insert(7,"-");
myString.Insert(13,"-");
myString.Insert(18,"-");
My first thought is:
String s = "731478718861993983";
s = s.Insert(3,"-");
s = s.Insert(8,"-");
s = s.Insert(13,"-");
s = s.Insert(18,"-");
(don't remember if index is zero-based, in which case you should use my values -1)
but there is probably some easier way to do this...
If the position of "-" is always the same then you can try
string s = "731478718861993983";
s = s.Insert(2, "-");
s = s.Insert(7, "-");
s = s.Insert(12, "-");
s = s.Insert(17, "-");
Here's how I'd do it; it'll only work if you're storing the numbers as something which isn't a string as they're not able to be used with format strings.
string numbers = "731478718861993983";
string formattedNumbers = String.Format("{0:##-####-####-####-####}", long.Parse(numbers));
Edit: amended code, since you said they were held as a string in your your original question

How to split for only one string without using arrays

I've a string 01-India. I want to split on '-' and get only the code 01. How can I do this. I'm a .net newbie. Split function returns a array. Since I need only one string, how can this be done. Is there a ingenious way to do it using split only. Or do I've to use substring only?
Other possibility is
string xy = "01-India";
string xz = xy.Split('-')[0];
You can search for the first occurence of - and then use the method substring to cut the piece out.
var result = input.Substring(0, input.IndexOf('-'))
string str = "01-India";
string prefix = null;
int pos = str.IndexOf('-');
if (pos != -1)
prefix = str.SubString(0,pos);
var str = "01-India";
var hyphenIndex = str.IndexOf("-");
var start = str.substring(0, hyphenIndex);
or you can use regular expression if it is a more complicated string pattern.
Something like this?
var s = "01-India";
var result = s.SubString(0, s.IndexOf("-"));
Since you don't want to use arrays, you could do an IndexOf('-') and then a substring.
string s = "01-India"
int index = s.IndexOf('-');
string code = s.Substring(0, index);
Or, for added fun, you could use String.Remove.
string s = "01-India"
int index = s.IndexOf('-');
string code = s.Remove(index);
string value = "01-India";
string part1 = value.Split('-')[0];

remove last word in label split by \

Ok i have a string where i want to remove the last word split by \
for example:
string name ="kak\kdk\dd\ddew\cxz\"
now i want to remove the last word so that i get a new value for name as
name= "kak\kdk\dd\ddew\"
is there an easy way to do this
thanks
How do you get this string in the first place? I assume you know that '' is the escape character in C#. However, you should get far by using
name = name.TrimEnd('\\').Remove(name.LastIndexOf('\\') + 1);
string result = string.Join("\\",
"kak\\kdk\\dd\\ddew\\cxz\\"
.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries)
.Reverse()
.Skip(1)
.Reverse()
.ToArray()) + "\\";
Here's a non-regex manner of doing it.
string newstring = name.SubString(0, name.SubString(0, name.length - 1).LastIndexOf('\\'));
This regex replacement should do the trick:
name = Regex.Replace(name, #"\\[a-z]*\\$", "\\");
Try this:
const string separator = "\\";
string name = #"kak\kdk\dd\ddew\cxz\";
string[] names = name.Split(separator.ToCharArray(),
StringSplitOptions.RemoveEmptyEntries);
string result = String.Join(separator, names, 0, names.Length - 1) + separator;
EDIT:I just noticed that name.Substring(0,x) is equivalent to name.Remove(x), so I've changed my answer to reflect that.
In a single line:
name = name = name.Remove(name.Remove(name.Length - 1).LastIndexOf('\\') + 1);
If you want to understand it, here's how it might be written out (overly) verbosely:
string nameWithoutLastSlash = name.Remove(name.Length - 1);
int positionOfNewLastSlash = nameWithoutLastSlash.LastIndexOf('\\') + 1;
string desiredSubstringOfName = name.Remove(positionOfNewLastSlash);
name = desiredSubstringOfName;
My Solution
public static string RemoveLastWords(this string input, int numberOfLastWordsToBeRemoved, char delimitter)
{
string[] words = input.Split(new[] { delimitter });
words = words.Reverse().ToArray();
words = words.Skip(numberOfLastWordsToBeRemoved).ToArray();
words = words.Reverse().ToArray();
string output = String.Join(delimitter.ToString(), words);
return output;
}
Function call
RemoveLastWords("kak\kdk\dd\ddew\cxz\", 1, '\')
string name ="kak\kdk\dd\ddew\cxz\"
string newstr = name.TrimEnd(#"\")
if you working with paths:
string name = #"kak\kdk\dd\ddew\cxz\";
Path.GetDirectoryName(name.TrimEnd('\\'));
//ouput: kak\kdk\dd\ddew
string[] temp = name.Split('\\');
string last = "\\" + temp.Last();
string target = name.Replace(last, "");
For Linq-lovers: With later C# versions you can use SkipLast together with Split and string.Join:
var input = #"kak\kdk\dd\ddew\cxz\";
string result = string.Join( #"\", input
.Split( #"\", StringSplitOptions.RemoveEmptyEntries )
.SkipLast( 1 ))
+ #"\";

Categories