This question already has an answer here:
String replace not working [duplicate]
(1 answer)
Closed 7 years ago.
I just started learning C# and I am trying to understand how to use the ref and out .
I tried to build the simplest function I could think of but I'm getting error and I can't understand why.
namespace cscheck
{
class Program
{
static void Main(string[] args)
{
string check = "Check noob wallak";
Console.WriteLine(check);
swap(ref check, "noob", "boon");
Console.WriteLine(check);
}
static void swap(ref string origin ,string x, string y)
{
origin.Replace(x, y);
}
}
}
But the results I get are :
Check noob wallak
Check noob wallak
As I understand x and y are passed by value while check passed by reference, but the replace hasn't ouccred and I can figure why.
Because Replace doesn't mutate, it creates a new string. Try:
origin = origin.Replace(x, y);
Replace() returns a string. You must use it as the result as so :
origin = origin.Replace(x, y);
.Replace returns a new string, it does not modify the original. Strings are immutable.
Related
This question already has answers here:
Why I need to use ref keyword in both declaration and Call?
(6 answers)
Closed 4 months ago.
I am attempting to make a method that's used to search for a word in a paragraph that asks the user for the word but I get the error "Argument 2 must be passed with the 'ref' keyword." when trying to call my GetString method from my input.cs. I'm trying to associate the word "find" for the parameter but I'm having a hard time trying to figure this out and would appreciate any help.
Below is my SearchWord method in Program.cs.
public static void SearchWord(Dictionary<string, int> word)
{
string find = "";
string choice = Input.GetString("\nWhat word are you searching for? ", find);
if (word.ContainsKey(choice))
{
PrintKeyValueBar(choice, word[choice]);
string[] sentences = GetSpeech().Split(new char[] {'.',' ',',','!','?',':','\n','\t','\r'});
foreach (string sentence in sentences)
{
if (sentence.Contains(choice))
{
Console.WriteLine(sentence);
}
}
}
else
{
Console.WriteLine($"{choice} is not found.");
}
}
Thank you in advance for the assistance.
EDIT. Adding the GetString method in Input.cs
public static void GetString(string prompt, ref string value)
{
while (true)
{
value = GetInput(prompt);
if (ValidString(prompt))
{
break;
}
Console.WriteLine("That's not right");
}
}
Class instructions state "Use GetString to get the word from the
user!" but when trying to do so I get the error.
I have tried string ref find = "";, ref find = ""; ref string find "";
ref is a keyword in C Sharp to pass a value-type varibale like a ref-type variable to a method call. That means, you are able to change the value of your variable inside the method.
So try Input.GetString("\nWhat word are you searching for? ", ref find);.
Howevery, I don't see the purpose of ref in your code sniped.
Maybe you can post your GetString Method as well!
This question already has answers here:
string.Replace (or other string modification) not working
(4 answers)
Closed 3 years ago.
I want to replace characters in a string iteratively using the string.Replace() function in a for loop however every iteration the string itself resets and no changes made in the previous loop stay. Ending up in the string undergoing no changes overall.
I've tried making the string a class member but that didn't work,
static void Main(string[] args)
{
int i;
string strOne = "abcdefg";
for (i=0; i < (strOne.Length - 1); i++)
{
string c = Convert.ToString(strOne[i]);
strOne.Replace(c, "1");
}
}
I expect the output of 1111111 but instead i get abcdefg.
When you call string.Replace(), it does not modify the string itself. Instead, it returns the string with the replaced characters. Therefore, you need to do this: strOne = strOne.Replace(c, "1");
This question already has answers here:
Evaluating string "3*(4+2)" yield int 18 [duplicate]
(13 answers)
Closed 4 years ago.
I'm starting out with coding and trying to make a very basic calculator. I want to run it in a cmd by calling it up with two numbers. So, in the correct directory, I would type "BasicCal 2 + 5" to run it.
This is the code in C#
using System;
public class BasicCal
{
public static void Main(string [] args)
{
Console.Write(args[0] + args[1] + args[2]);
Console.ReadKey();
}
}
Cmd then just prints "2+5" so I guess C# doesn't see an operator as an argument.
So I just need to know how to make C# recognize an operator when it's given as a parameter. Thanks in advance.
There are couple of problems here.
A) There is no sort of built-in way that allows C# compiler to understand what you're doing here so you'd have to implement the logics of parsing string argument with the sign:
switch(args[1])
{
case "+":
{
...
break;
}
case "-":
{
...
break;
}
... etc
}
B) Args are just strings so if we just do something like args[0] + args[1] the C# compiler doesn't know that its working with numbers and runs an overloaded + operator for string which does string concatenation.
This question already has answers here:
Identify if a string is a number
(26 answers)
Closed 6 years ago.
I am writing a small console application in C# and it requires two numeric parameters/arguments to be passed to it. I am checking for no params, more than 2 params, if two params. I am also converting those params if 2 returned to numeric for calculations I'm doing. One thing I'm not doing is verifying what's being passed is a number so assume program will crap out if I pass a letter. Is there a look routing I can just run to verify the params passed are in deed able to be numbers? I can handle the kick out from there but curious how you check if an argument CAN be a number or not.
Thanks.
JR
I would simplify this task as follows:
Create custom Convert method:
static double Convert(string s)
{
double result;
if (!double.TryParse(s, out result))
result = double.NaN;
return result;
}
Use it in Main:
static void Main(string[] args)
{
var doubles = args.Select(a => Convert(a)).ToArray();
var valid = doubles.All(a => !double.IsNaN(a));
}
Here's one way;
static void Main(string[] args)
{
foreach (var arg in args)
{
int asInt;
// Returns "true" if arg can be parsed as an int and false otherwise;
// If you want to allow doubles you can also try double.TryParse in a similar manner
if (int.TryParse(arg, out asInt))
{
// Handle
}
// Failed to parse argument as an int
else
{
throw new ArgumentException("arg not an int");
}
}
}
You could also use a Regex:
static void Main(string[] args)
{
// Make sure this can is either an int or a double
var regex = new Regex(#"^-?(([0-9]+)|([0-9]+\.[0-9]+(e[0-9]+)?))$");
foreach (var arg in args)
{
if (!regex.IsMatch(arg))
throw new ArgumentException("arg " + arg + " is not an int or double");
}
}
Note a few important features of this regex:
- The "#" literal symbol in front of the regex string
- The ^ and $ to mark the beginning and end of lines - i.e. the string must contain only a number or only a double
- This bans empty strings as well
Edit: I edited the Regex to optionally allow for something like "1.0e100" or "-123", which, as pointed out in the comments, are also perfectly valid ints and doubles. Also, as pointed out in the comments, it's probably better to use int.TryParse or double.TryParse rather than reinventing the wheel.
There's also Char.IsDigit which always feels cleaner to me than checking for a failed parsing attempt. If you care about micro-optimizing, char.IsDigit is probably faster than parsing an invalid string too.
Or, if negative numbers or non-whole numbers are your thing, you can use char.IsNumber
See: https://msdn.microsoft.com/en-us/library/7f0ddtxh(v=vs.110).aspx
public static void Main(string[] args)
{
for(int i = 0; i < args.Length; i++)
{
if(args[i].All((c) => char.IsDigit(c))
{
//It's a number.
}
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am struggling how to use "ref" (to pass argument by reference) in real app. I would like to have simple and mainly meaningful example. Everything I found so far could be easily redone with adding return type to the method.
Any idea someone?
Thanks!
The best example coming in my mind is a function to Swap two variables values:
static void Swap<T>(ref T el1, ref T el2)
{
var mem = el1;
el1 = el2;
el2 = mem;
}
Usage:
static void Main(string[] args)
{
string a = "Hello";
string b = "Hi";
Swap(ref a, ref b);
// now a = "Hi" b = "Hello"
// it works also with array values:
int[] arr = new[] { 1, 2, 3 };
Swap(ref arr[0], ref arr[2]);
// now arr = {3,2,1}
}
A function like this one, cannot be done without the ref keyword.
One possibly corner-case example: Interlocked.Increment. Without passing the variable by reference, there's no way of performing the increment atomically.
I can't say I've used ref very much myself, to be honest - I generally steer clear of the need to return multiple values, and even then out is usually sufficient. Many of the cases where I've seen ref used, it's been due to the author not understanding how arguments are passed in .NET when it comes to reference types.
The TryParse methods built into the framework are typical examples. They use out instead of ref but it is the same semantics, it's just that the caller doesn't need to initialize the value. Example:
int result;
bool isSuccess = int.TryParse("some string", out result);
if (isSuccess)
{
// use the result here
}
As you can see the function returns a boolean indicating whether the operation succeeds but the actual result is returned as out parameter.
public static void Main(string args[])
{
int i=0;
AddSomething(ref i);
AddSomething(ref i);
AddSomething(ref i);
AddSomething(ref i);
string mystr = "Hello";
AddSomeText(ref mystr);
Console.WriteLine(mystr);
Console.WriteLine("i = {0}", i);
}
public static void AddSomeText(ref string str)
{
str+= " World!";
}
public static void AddSomething(ref int ii)
{
ii+=1;
}
One of the most common places I see it, is in Save methods of some frameworks.
The reason is that in many cases it is not actually possible to maintain the same object over a save call, if the object is being serialized to another machine and then comes back as a new instance (perhaps with some extra defaults). In that case you need the ref to make it obvious that the original reference is no longer valid.
As for its NECESSITY, I can't come up with an example where it would be required. Most places out is just fine.
I think a good example would be trampolining.
This is where you take a recursive function and rework it to a method that is repeatidly called on a set of values. The reason being that instead of going into the stack very deeply the stack remains flat because you return after every call instead of calling yourself.
Regards GJ