What does "str" + x + "str" mean? - c#

Why would you use "str" + x + "str" in ImageLocation.
private void CreateEnemies()
{
Random rnd = new Random();
int x = rnd.Next(1, kindOfEnemies + 1);
PictureBox enemy = new PictureBox();
int loc = rnd.Next(0, panel1.Height - enemy.Height);
enemy.SizeMode = PictureBoxSizeMode.StretchImage;
enemy.ImageLocation = "Aliens/" + x + ".png";
}
I don't understand why you would use this.

The + operator is used for adding. If used on a string it will not add two strings, but concatenate them:
var text = "Hello" + "World" + "String";
Console.WriteLine(text); // Prints "HelloWorldString"
So the code above just constructs a string. Because the variable x is not of type int, .Net will automatically call .ToString().
int x = 5;
var text1 = "Aliens/" + x +".png"; // is the same as below.
var text2 = "Aliens/" + x.ToString() +".png"; // is the same as above.
Console.WriteLine(text); // Prints "Aliens/5.png"
In C# version 6 and above you can also use string interpolation, which makes things clearer:
var text1 = $"Aliens/{x}.png"; // is the same as below.
var text2 = $"Aliens/{x.ToString()}.png"; // is the same as above.
With string interpolation, you can embed variables into a string, by placing them into curly braces.
Note that the string has to start with a $.

+ is used for string concatenation

This is a way to randomize the image of the alien that you get.
Your solution has a folder called Aliens with files named 0.png, 1.png, 2.png, and so on in it. Each file has an image of an "alien", which your program loads into a PictureBox. Your code picks one of these files at random, using string concatenation.
With C# 6 and newer you can use string interpolation:
enemy.ImageLocation = $"Aliens/{x}.png";

It is concatenating strings together. So "Aliens/" + The string value of 'x' + ".png" are being 'added' together.
Lets say:
int x = 1
The output string would be
"Aliens/1.png"

Related

remove all characters after X character

Please check variable "mystr" value where a "-" sign between two part of numbers. I want to find "-" then remove all character after that then I want find same "-" and remove all Character from first to till that. I know it's simple but not getting exact solution on c# due to I am new.
public void test()
{
string mystr = "1.30-50.50";
//first output I want is- "1.30"
//second output I want is- "50.50"
}
Use string.Split method:
var mystr = "1.30-50.50";
var result = mystr.Split('-');
var a = result[0]; //"1.30"
var b = result[1]; //"50.50"
you can also String.IndexOf method
string mystr = "1.30-50.50";
int indexOfDash = mystr.IndexOf('-');
string firsResult = mystr.Substring(0, indexOfDash);
string secondResult = mystr.Substring(indexOfDash + 1, mystr.Length - indexOfDash - 1);

String IndexOf and Substring C#

I'm working on to read a textfile which contains this line of string. And to fetch its value to my integer variables.. I want to try to avoid using Class or Arrays.
string cont = "[]val1:1val2:0val3:1";
int split = cont.IndexOf("val3:");
int val3 = Int32.Parse(cont.Substring(split + 5)); // this line successfully convert string to int
cont.Remove(split);
Console.WriteLine("Value3: " + val3 + " Content: " + cont);
split = cont.IndexOf("val2:");
int val2 = Int32.Parse(cont.Substring(split + 5)); // LINE 21
cont.Remove(split);
Console.WriteLine("Value2: " + val2 + " Content: " + cont);
split = cont.IndexOf("val1:");
int SilverCoins = Int32.Parse(cont.Substring(split + 5));
cont.Remove(split);
Console.WriteLine("Value1: " + val1 + " Content: " + cont);
When I run this code, I get an Unhandled Exception which states Input string was not in a correct format, at System.Int32.Parse(String s), line 21. :(
So, my desired output should be
Value3: 1 Content: []val1:1val2:0
Value2: 0 Content: []val1:1
Value1: 1 Content: []
Your problem is in this code cont.Remove(split);
Strings are immutable, so you need to reassign new value.
In order to fix it you need to write
cont = cont.Remove(split);
You aren't putting the remove result back into the string, try doing this:
cont = cont.Remove(split);
When we perform some action on string it does not make changes in the same string instance. Instead it returns a new string instance. This concept is known as Immutability.
When you do
cont.Remove(split);
it does not update cont. Instead it returns updated string which you need to capture like this
cont = cont.Remove(split);
Restoring the cont value after calling the Remove method is missing.
Modified Code:
string cont = "[]val1:1val2:0val3:1";
int split = cont.IndexOf("val3:");
int val3 = Int32.Parse(cont.Substring(split + 5)); // this line successfully convert string to int
cont = cont.Remove(split);
Console.WriteLine("Value3: " + val3 + " Content: " + cont);
split = cont.IndexOf("val2:");
int val2 = Int32.Parse(cont.Substring(split + 5)); // but this line fails to convert from string to int..
cont = cont.Remove(split);
Console.WriteLine("Value2: " + val2 + " Content: " + cont);
split = cont.IndexOf("val1:");
int val1 = Int32.Parse(cont.Substring(split + 5));
cont = cont.Remove(split);
Console.WriteLine("Value1: " + val1 + " Content: " + cont);
Two ways you can fix the problem.
C# strings are immutable, so you have to modify your code to
cont = cont.Remove(split);
Another approach(might be best for your case), when using the SubString specify length, so you get specified number of characters.
split = cont.IndexOf("val2:");
int val2 = Int32.Parse(cont.Substring(split + 5, 1));
0val3:1 is not a valid number, therefore int.Parse fails. If you need to extract the 0 from the beginning of this string, you can refer to Parse an integer from a string with trailing garbage .
Also, the result of cont.Remove(split); is never used in your code snippet, and thus does nothing but waste CPU cycles. Considering you notice this behavior in the Console.WriteLine, and simply complain about an exception, I can only assume this was intentional?
Note that it looks like you're trying to extract key-value pairs from a string. A regular expression similar to val([^:]+):([0-9]+) might be a better tool here.
Alternatively, you can split on val and take the left/right of the colon. Something like:
var vals = cont.Split(new[] {"val"}, StringSplitOptions.None)
.Skip(1) //ignore any garbage at the beginning
.Select(x => x.Split(':'))
.ToDictionary(x => x[0], x => int.Parse(x[1]));

Is there built-in method to add character multiple times to a string?

Is there a built-in function or more efficient way to add character to a string X number of times?
for example the following code will add '0' character 5 times to the string:
int count = 5;
char someChar = '0';
string myString = "SomeString";
for(int i=0;i<count;i++)
{
myString = someChar + myString;
}
Use PadLeft() or PadRight()
An example for PadRight():
int count = 5;
char someChar = '0';
string myString = "SomeString";
myString = myString.PadRight(count + myString.Length, someChar);
// output -> "SomeString00000"
Remember the first parameter of either method is the total string length required hence why I am adding count to the original string length.
Likewise if you want to append the character at the start of the string use PadLeft()
myString = myString.PadLeft(count + myString.Length, someChar);
// output -> "00000SomeString"
string.Concat(Enumerable.Repeat("0", 5));
will return
"00000"
Refered from :Is there a built-in function to repeat string or char in .net?
You can also do it as:
string line = "abc";
line = "abc" + new String('X', 5);
//line == abcXXXXX
Take a look here, You can use PadRight() / PadLeft();
int count = 5;
char someChar = '0';
string myString = "SomeString";
var stringLength = myString.Length;
var newPaddedStringRight = myString.PadRight(stringLength + count, '0');
//will give SomeString00000
var newPaddedStringLeft = myString.PadLeft(stringLength + count, '0');
//will give 00000SomeString
Remember, a string is Immutable, so you'll need to assign the result to a new string.
You could also use StringBuilder. As the string size increases the += incurs a cost on array copy.

C# indexof not working

When I run this through the debugger the result for string CL_S and string NA_S are the same value, which is 122.13.
Not sure why it does this since the indexOf is different - the second one does not exist.
text = "4R|1|^^^100^CL_S|122.13|38||||F|||20070628114638"
string str = text;
try
{
int a_first = str.IndexOf("^^^100") + "^^^100".Length + 1;
string str_a = str.Substring(a_first);
string[] words_a = str_a.Split('|');
string CL_S = words_a[1];
int b_first = str.IndexOf("^^^101") + "^^^101".Length + 1;
string str_b = str.Substring(b_first);
string[] words_b = str_b.Split('|');
string NA = words_b[1];
Step through a debugger and look at the values of the variables.
Here's a quick analysis which should help point you towards the problem:
a_first has the value 12
str_a has the value "CLS_S|122.13|..."
b_first has the value 6 (Note that you are adding -1 + 6 + 1; the -1 is from the IndexOf that doesn't have a match. IndexOf is working just fine.)
str_b has the value "^^100^CL_S|122.13|..."
When you split either str_a or str_b on a |, the second element (index [1]) of both will be 122.13.
In the second case the IndexOf call returns -1, and adding seven to that puts you at index 6.
When you use that in the Substring call you will get ^^100^ prefixed to the string, compared to the string from the first case.
As that doesn't contain any | characters, splitting will only give a different result for the first item in the array, and as you are getting the second item it will be the same as in the first case.
Run this on IDEONE https://ideone.com/F6KDNS
using System;
public class Test
{
public static void Main()
{
string str = "4R|1|^^^100^CL_S|122.13|38||||F|||20070628114638" ;
int a_first = str.IndexOf("^^^100") + "^^^100".Length + 1;
string str_a = str.Substring(a_first);
string[] words_a = str_a.Split('|');
string CL_S = words_a[1];
Console.WriteLine(a_first);
Console.WriteLine(str_a);
Console.WriteLine(CL_S);
Console.WriteLine();
int b_first = str.IndexOf("^^^101") + "^^^101".Length + 1;
string str_b = str.Substring(b_first);
string[] words_b = str_b.Split('|');
string NA = words_b[1];
Console.WriteLine(b_first);
Console.WriteLine(str_b);
Console.WriteLine(NA);
}
}
I got this:
12
CL_S|122.13|38||||F|||20070628114638
122.13
6
^^100^CL_S|122.13|38||||F|||20070628114638
122.13
So you can see that the second IndexOf returns -1 => b_first is 6. This means that you the two strings in both have their first break at
CL_S| & ^^100^CL_S|
And thus both have second item = 122.13

C# split string on X number of alpha numeric values

this might be simple question I have 3 strings
A123949DADWE2ASDASDW
ASDRWE234DS2334234234
ZXC234ASD43D33SDF23SDF
I want to split those by the first 8 characters and then the 10th and 11th and then combine them into one string.
So I would get:
A123949DWE
ASDRWE23S2
ZXC234AS3D
Basically the 9th character and anything after the 12th character is removed.
You can use String.Substring:
s = s.Substring(0, 8) + s[10] + s[11]
Example code:
string[] a = {
"A123949DADWE2ASDASDW",
"ASDRWE234DS2334234234",
"ZXC234ASD43D33SDF23SDF"
};
a = a.Select(s => s.Substring(0, 8) + s[10] + s[11]).ToArray();
Result:
A123949DWE
ASDRWE23S2
ZXC234AS3D
So let's say you have them declared as string variables:
string s1 = "A123949DADWE2ASDASDW";
string s2 = "ASDRWE234DS2334234234";
string s3 = "ZXC234ASD43D33SDF23SDF";
You can use the substring to get what you want:
string s1substring = s1.Substring(0,8) + s1.Substring(9,2);
string s2substring = s1.Substring(0,8) + s1.Substring(9,2);
string s3substring = s1.Substring(0,8) + s1.Substring(9,2);
And that should give you what you need. Just remember, that the string position is zero-based so you'll have to subtract one from the starting position.
So you could do:
string final1 = GetMyString("A123949DADWE2ASDASDW");
string final2 = GetMyString("ASDRWE234DS2334234234");
string final3 = GetMyString("ZXC234ASD43D33SDF23SDF");
public function GetMyString(string Original)
{
string result = Original.Substring(12);
result = result.Remove(9, 1);
return result;
}

Categories

Resources