Is there a quick way to pack an array of strings to a string?
More specifically,I have an array of strings like this:
string[] Operators = {"+","-","x","/"} and I would like to pack it to
string sOperators = "+-x/"
Of course, the obvious way is to read each item in the array and put it in the string individually, but is there a better way that people smarter than me can think of?
I have tried:
string sOperators="";
String.Join(sOperators,Operators);
Unfortunately, that won't work for me. Any thought?
Your code sample could just be incomplete but based on you've posted the problem is that you're not assigning the joined string anywhere. I think the following will do what you want;
string joined = String.Join(sOperators, Operators);
Join returns a new string, it does not make any changes to the arguments you pass it. You need to assign the return value to some field, property, constant, or variable in order to produce the desired result.
You can use String.Concat(Operators) (MSDN http://msdn.microsoft.com/en-us/library/k9c94ey1.aspx)
You can indeed use String.Join for this:
string sOperators = string.Join("", Operators);
I guess you just forgot to assign the result to a variable.
Related
I have the following field that is calling the database Phone_Number. I would like to remove the 1- when the number is displayed.
So instead of displaying 1-###-###-####, I would like to display ###-###-####.
I tried the following:
string x= Phone_Number;
x.Remove(0,1);
Response.Write(x);
However, it keeps displaying 1-###-###-####.
What am I doing wrong?
Strings are immutable in C# - String.Remove call does not modify original string. It creates the new string in which specified characters are deleted and returns it. You should display result of this method call instead:
Response.Write(x.Remove(0,2)); // you should remove 2 characters
Or
Response.Write(x.Substring(2));
You need to set the result to x. strings are immutable in C#:
x = x.Remove(0,1)
Another method would be:
if (x.StartsWith("1-")
x = x.Remove(0,2);
This has the benefit of doing nothing if you get a phone number without the leading 1-.
Thanks to commenter for pointing out my error.
As you see there are too many ways to remove substrings from strings. A new way that you can also use is a Regular Expression just in case the value you want to remove have a complex pattern in the future.
var x = phoneNumber;
var result = Regex.Match(x, #"^(1-)?(.*)$").Groups[2].Value;
I'm trying to make a list in string to get the usernames like this:
string[] whitelisted = { "example", "exampøle222", "example245"};
if (sentRequest.Sender.Username.ToLower().Contains(whitelisted))
You are checking if the username contains the list. You should be checking that the list contains the username.
whitelisted.Contains(sentRequest.Sender.Username.ToLower())
Your comparison is backwards. You need to see whether the array contains the string .
You probably want to check that the sentRequest.Sender.Username.ToLower() is present in the whitelisted list, right?
Then make it inverted if (whitelisted.Contains(sentRequest.Sender.Username.ToLower()))
The error you get says that the method you are calling i.e. string.Contains() can accept a string but cannot accept an array string[].
It can be done quite simply using the LINQ aggregate function.
string[] strings = {"example1","example2"};
string result = strings.Aggrigate((l,r)=>l+r);
You could also use the String.Join method
string[] strings = {"example1","example2"};
string result = String.Join("",strings);
However when I look at the rest of your code I would recommend solving the problem something like this.
if(whitelisted.IndexOf(sentRequest.Sender.Username.ToLower()) != -1)
That if statement will only be executed if the Username is in the white list.
I have a string in the following format:
message:action
How can I parse this string and get the second part only?
The action might be different the first part will always be the same: message:
Is this a correct way?
string value="message:action";
string[] result = value.Split(':');
string action = result[1];
Yes it is. Or, since the first part is always the same, you could simply use substring:
value.SubString(8);
That solution is fine, but it's a little more work than necessary. If you know that the string will always start with "message:", why not just do this:
var action = value.Substring(8);
However, if the string that comes before the : might change, but you still only care about what comes after it, you could do this:
var action = value.Substring(value.IndexOf(':') + 1);
Yes, your solution will work. However, if the first part is always the same, another possibility is to use Substring as pswg's answer mentions.
If you know that the string will start with message: you can do this:
String value="message:action";
String result = value.Replace("message:","");
It's OK, although if you worry about there being colons in the content (e.g., "message:action:do this"):
string value="message:action";
string[] result = value.Split(':');
string action = value.Substring(result[0].Length);
(this is of course if it's not always starting with "message:")
If you want to have self-documenting code, you can use regex (so you don't think in the future, what the heck is this code and why do I take second part).
string value = "message:action";
string action = Regex.Match(value, "(?<=^message:).*").Value; // will throw exception in case if someday format changes
I'm adding one more answer for legibility. There are several correct answers in the thread so far.
Just to offer a very readable alternative at very little cost of performance consider the following:
string value = "message:action";
string action = value.Split(':').Skip(1);
Is it possible to replace a substring in a string without assigning a return value?
I have a string:
string test = "Hello [REPLACE] world";
And I want to replace the substring [REPLACE] with something else:
test = test.replace("[REPLACE]", "test");
This works fine, but how can I do it without assigning the return value to a variable?
I want something like this:
test.replace("[REPLACE]", "test");
As mentioned by dlev, you can't do this with string as strings are immutable in .NET - once a string has been constructed, there's nothing you can do (excluding unsafe code or reflection) to change the contents. This makes strings generally easier to work with, as you don't need to worry about defensive copying, they're naturally thread-safe etc.
Its mutable cousin, however, is StringBuilder - which has a Replace method to perform an in-object replacement. For example:
string x = "Hello [first] [second] world";
StringBuilder builder = new StringBuilder(x);
builder.Replace("[first]", "1st");
builder.Replace("[second]", "2nd");
string y = builder.ToString(); // Value of y is "Hello 1st 2nd world"
You can't, because string is immutable. It was designed so that any "changes" to a string would actually result in the creation of a new string object. As such, if you don't assign the return value (which is the "updated" string, actually copy of the original string with applied changes), you have effectively discarded the changes you wanted to make.
If you wanted to make in-place changes, you could in theory work directly with a char[] (array of characters), but that is dangerous, and should be avoided.
Another option (as pointed out by Mr. Skeet below) is to use StringBuilder and its Replace() method. That being said, simple replacements like the one you've shown are quite fast, so you may not want to bother with a StringBuilder unless you'll be doing so quite often.
Strings in .NET are immutable. They cannot be edited in-line.
The closest you can get to in-line editing is to create a StringBuilder from a string. In-line fiddles with its contents and then get it to spit a string back out again.
But this will still produce a new string rather than altering the original. It is a useful technique, though, to avoid generating lots of intermediary strings when doing lots of string fiddling, e.g. in a loop.
You can't. You have to assign the value, as strings are immutable.
Built-in reference types (C# reference)
You can't. Strings are immutable in .NET.
You can't, as in C# strings are immutable. Something like this would violate that.
You need to have the return type of string, because the one you're working with cannot change.
Here is the code to fetch a string from HTML content and pass it to StringBuilder and set the value from your variable. You cannot do string.replace. You have to use StringBuilder while manipulating. Here in the HTML page I added [Name] which is replaced by Name from code behind. Make sure [Name] is unique or you can give any unique name.
string Name = txtname.Text;
string contents = File.ReadAllText(Server.MapPath("~/Admin/invoice.html"));
StringBuilder builder = new StringBuilder(contents);
builder.Replace("[Name]", Name);
StringReader sr = new StringReader(builder.ToString());
I have a little chunk of code (see below) that is returning the string:
string.Format("{0}----{1}",3,"test 2");
so how do I get this to actually "Execute"? To run and do the format/replacement of {0} and {1}?
My Code snippet:
StringBuilder sb = new StringBuilder();
sb.Append("{0}----{1}\",");
sb.AppendFormat(ReturnParamValue(siDTO, "siDTO.SuggestionItemID,siDTO.Title"));
string sbStr = "=string.Format(\""+sb.ToString()+");";
yes, ReturnParamValue gives the actually value of the DTO.
Anyways, I've taken a look at the following (but it doesn't say how to execute it:
How to get String.Format not to parse {0}
Maybe, I just should put my code snippet in a method. But, what then?
Why are you including String.Format in the string itself?
If you're looking for a generic "let me evaluate this arbitrary expression I've built up in a string" then there isn't a simple answer.
If, instead, you're looking at how to provide the parameters to the string from a function call, then you've got yourself all twisted up and working too hard.
Try something like this, based on your original code:
string result
= string.Format(
"{0}----{1}",
ReturnParamValue(siDTO, "siDTO.SuggestionItemID,siDTO.Title"));
Though, this won't entirely work since your original code seems to be only providing a single value, and you have two values in your format string - the {0} will be replaced with the value from your function, and {1} left unchanged.
What output are you expecting?
Does your ReturnParamValue() function try to return both the label and the value in a single string? If it does, and if they're comma separated, then you could try this:
var value = ReturnParamValue(siDTO, "siDTO.SuggestionItemID,siDTO.Title"));
var pieces = string.Split(',');
string result
= string.Format( "{0}----{1}", pieces[0], pieces[1]);
Though this is seriously working too hard if ReturnParamValue() is a method you control.
Update Fri 6 August
Check out the declaration for string.Format() as shown on MSDN:
public static string Format(
string format,
params Object[] args
)
Unlike the special casing you might have seen in C for printf(), there's nothing special or unusual about the way string.Format() handles multiple parameters. The key is the params keyword, which asks the compiler to provide a little "syntactic sugar" where it combines the parameters into an array for you.
Key here is that the wrapping doesn't happen if you're already passing a single object[] - so if you wanted to, you could do something like this:
object[] parameters
= ReturnParamValues(siDTO, "siDTO.SuggestionItemID,siDTO.Title");
string result
= string.Format("{0}----{1}----{2}", parameters);
Though, if I saw something like this in any codebase I maintained, I'd be treating it as a code-smell and looking for a better way to solve the problem.
Just because it's possible doesn't mean it's advisable. YMMV, of course.
I don't think you can execute it. Java is not really a interpreted language.
You may make use of scripting languages (which can even embed in your Java app as I know, start from JDK6) for such purpose, like Groovy
You could use RegEx to parse the three parameters out of the string, and then pass them to a real, actual string.Format method :-)
It looks like what you want is something like this:
string sbStr = string.Format("{0}----{1}", siDTO.SuggestionItemID, siDTO.Title);
Maybe i didn't understand your question completely, but it sounds like you need to format a format-string. If that's true you could maybe try something like this:
int width = 5;
string format = String.Format("{{0,{0}}}----{{1,{0}}}", width);
string result = String.Format(format, "ab", "cd");
So the trick is simply to escape the { or } by using a double {{ or }}.