How to swap values of two string variables without a temp variable? - c#

For example, I have two string variables:
string a = " Hello ";
string b = " World ";
How can I swap it without a temporary variable?
I found an example, but it used a third variable for the length of a:
int len1 = a.Length;
a = a + b;
b = a.Substring(0, len1);
a = a.Substring(len1);
How can I do that?
UPD, suggested solution for decimal data type, in ma case i've asked about string data type.

You can use SubString without using a temp variable, like this:
string a = " Hello ";
string b = " World ";
a = a + b;//" Hello World "
b = a.Substring(0, (a.Length - b.Length));//" Hello "
a = a.Substring(b.Length);//" World "

Just use some other means of swapping.
string stringOne = "one";
string stringTwo = "two";
stringOne = stringOne + stringTwo;
stringTwo = stringOne.Substring(0, (stringOne.Length - stringTwo.Length));
stringOne = stringOne.Substring(stringTwo.Length);
// Prints stringOne: two stringTwo: one
Console.WriteLine("stringOne: {0} stringTwo: {1}", stringOne, stringTwo);

string str1 = "First";
string str2 = "Second";
str1 = (str2 = str1 + str2).Substring(str1.Length);
str2 = str2.Substring(0,str1.Length-1);

I'm fond of doing it this way although underneath it's using resources to make it fully thread-safe, and I wouldn't be surprised if it was using a local variable behind the scenes.
string str1 = "First";
string str2 = "Second";
str2 = System.Interlocked.Exchange(ref str1, str2);

Related

Converting a range of strings to int for addition

This is an extension of the question asked here:
Converting string to int and then back to string
I am now converting a range of string values to add all of them together. I obviously cannot do something like:
int Total;
string str1 = "1";
string str2 = "1";
string str3 = "1";
string str4 = "1";
string str5 = "1";
string str6 = "1";
...
...
void Start()
{
Total = int.Parse(str1) + int.Parse(str2) + .....
}
I am looking for a way to parse all the strings into int such that:
Total = int.Parse(str1 + str2 + str3 + ...)
How do I achieve this?
As long as you do not know how many values you will have, you cannot hardcode all the single values into independent variables.
Advice: You should really consider storing the data in the correct format, You approach should be working with integers instead of strings (using a List<int>). The code would be more bug resistant and more simple.
int Total = 0;
List<string> valuesToAdd = new List<string>(){
"1",
"4",
"1",
"99"
};
void Start()
{
Total = 0;
foreach(string stringValue in valuesToAdd)
{
Total += int.Parse(stringValue);
}
}

How to replace variable in user input with math operation?

I need replace variable in string from user. For example:
User input: Ssad asdsdqwdq jdiqwj diqw jd qwld j {price-40%} asd asd asd
I know how replace only {price} but I don't know how to replace other cases.
I need support these cases:
{price}
{price-xx%}
{price+xx%}
{price-xx}
{price+xx}
{price/xx}
{price*xx}
And user can use variable {price} many times.
After user submit text, my app replace variable {price} or calc {price-xx%} and create a new string.
If I understood your problem correctly then I think you can evaluate the whole expression without Replacing variables (might you have to change placements of variables)
First, add 'System.Data' name space in your project
then:
double price = 110;
double xx = 15;
double result = 0;
result = Convert.ToDouble(new DataTable().Compute($"({price-(price*xx)/100})", null));
Console.WriteLine("{price - xx%} = " + result);
result = Convert.ToDouble(new DataTable().Compute($"({price + (price * xx) / 100})", null));
Console.WriteLine("{price + xx%} = " + result);
result = Convert.ToDouble(new DataTable().Compute($"({price}-{xx})", null));
Console.WriteLine("{price - xx} = " + result);
result = Convert.ToDouble(new DataTable().Compute($"({price}+{xx})", null));
Console.WriteLine("{price + xx} = " + result);
result = Convert.ToDouble(new DataTable().Compute($"({price}/{xx})", null));
Console.WriteLine("{price / xx} = " + result);
result = Convert.ToDouble(new DataTable().Compute($"({price}*{xx})", null));
Console.WriteLine("{price * xx} = " + result);
https://github.com/davideicardi/DynamicExpresso/
static void Main(string[] args)
{
int price = 100;
Regex regex = new Regex(#"(?<=\{).*?(?=\})");
string userInput = "Hi. I want to buy your computer. I can't offer {price} USD, but I can offer {price-(price/100)*10} USD";
string text = userInput;
foreach (var item in regex.Matches(text))
{
string expression = item.ToString().Replace("price", price.ToString());
var interpreter = new Interpreter();
var result = interpreter.Eval(expression);
text = regex.Replace(text, result.ToString(),1);
text = ReplaceFirst(text, "{", string.Empty);
text = ReplaceFirst(text, "}", string.Empty);
}
Console.WriteLine("Result: " + text);
}
public static string ReplaceFirst(string text, string search, string replace)
{
int pos = text.IndexOf(search);
if (pos < 0)
{
return text;
}
return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}

String split// manipulation

string keywords = "heard";
string strText = "Have you not heard!! what I said?"
string[] words = strText.Split(' ');
string result = "";
for (int i = 0; i < words.Length; i++)
{
if (words[i].Contains(keywords))
result += "<span>" + words[i] + "</span>" + " ";
else
result += words[i] + " ";
}
I get following output:
Have you not <span>heard!!</span> what I said?
Desired output:
Have you not <span>heard</span>!! what I said?
Can someone guide how can I get the desired output. The strText can only be split with a space.
Use String.Replace
var result = strText.Replace(keywords, "<span>" + keywords + "</span>");
If you have many keywords to replace, then just do replacement in a loop:
string[] keywords = { "heard", "said" };
string result = "Have you not heard!! what I said?";
foreach(var keyword in keywords)
result = result.Replace(keyword, "<span>" + keyword + "</span>");
Alternative solution is regular expression replacement:
string keywords = "heard|said";
string result = "Have you not heard!! what I said?";
result = Regex.Replace(result, keywords, m => "<span>" + m.Value + "</span>");
Why are you even looping through all words? This will give you the same:
string strText = "Have you not heard!! what I said?";
string newText = strText.Replace("heard", "<span>heard</span>");

I have a string "pencil". the first three letters "pen" should change to "PEN". Can anyone help me?

I have a string "pencil". The first three letters pen should change to "PEN". Can anyone help me?
You can't "change" a string. You can create a new string and change some of the letters in-flight:
string s1 = "pencil";
string s2 = s1.Substring(0,3).ToUpper() + s1.Substring(3);
You can also, of course, overwrite the existing variable value:
string s1 = "pencil";
s1 = s1.Substring(0,3).ToUpper() + s1.Substring(3);
You can use String.Substring() and String.ToUpper() functions to achieve this
string str = "pencil";
int lettersCount = 3;
str = str.Substring(0, lettersCount ).ToUpper() + str.Substring(lettersCount );
Use Substring and ToUpper:
int numChars = 3;
string pencil = "pencil";
if (pencil.Length >= numChars)
pencil = pencil.Substring(0, numChars).ToUpper() + pencil.Substring(numChars);
using System.IO;
using System;
class Program
{
static void Main()
{
string word = "pencil";
string finalWord = word.Substring(0, 3).ToUpper() + word.Substring(3);
Console.WriteLine(finalWord); //PENcil
}
}
string s = "pencil";
string str = new string(s.Select((c, index) =>
{
if (index < 3)
return Char.ToUpper(c);
else
return c;
}).ToArray());
Console.WriteLine(str); // output: PENcil

Variable String.Format length

I have the following code:
var str = "ABC";
var n = 7;
var output = String.Format("{0,n}", str);
This should output the string
" ABC"
How should I change the line above?
Format strings are just strings too - you can define the format separately:
int n = 3;
string format = string.Format("{{0,{0}}}", n);
//or more readable: string format = "{0," + n + "}";
var output = string.Format(format, str);
Edit:
After your update it looks like what you want can also be achieved by PadLeft():
var str = "ABC";
string output = str.PadLeft(7);
Just write:
var lineLength = String.Format("{0," + n + "}", str);
var s="Hello my friend";
string leftSpace = s.PadLeft(20,' '); //pad left with special character
string rightSpace = s.PadRight(20,' '); //pad right with special character

Categories