I am sure its possible, but I haven't figured out how. How would I go about using string interpolation for scriptableObjects? Some basic code I have for it:
public class ScriptableCardBase : ScriptableObject
{
public string cardDes;
}
public class CardUI : MonoBehaviour
{
public List<ScriptableCardBase> card = new List<ScriptableCardBase>();
public Text desText;
public void DisplayCard(int i)
{
desText.text = card[i].cardDes;
}
}
For my cards, I just want to be able to display the damage of the card, or number of effects, etc. Here is a screenshot of what the SO Card looks like and where I try to input the string. Any help would be greatly appreciated!
CardSO
I guess a long questions short is, can I use string interpolation with scriptable objects?
What you want is to convert your string to its Formattable version.
You can do it via reflection or some sort of IL you want. Some start could be:
public static string ParseFromFormattable(this string str, object context) {
// Define a random char that is unlikely to appear on normal text.
const char weirdChar = '°'; // This will prepend the interpolation parameters
var outputStr = "";
// Split all the parts and iterate through them, using reflection to get the value from values inside '{}'
foreach (var part in GetStringParts()) {
if (part[0] == weirdChar) { outputStr += context.GetType().GetField(part.Substring(1)).GetValue(context).ToString(); }
else { outputStr += part; }
}
return "";
List<string> GetStringParts() {
var strParts = new List<string>();
var currentPart = "";
var writingParam = false;
foreach (var c in str) {
if (c == '{') {
if (currentPart != "") { strParts.Add(currentPart); }
currentPart = "";
writingParam = true;
}
else if (writingParam && c == '}') {
strParts.Add(weirdChar + currentPart);
currentPart = "";
writingParam = false;
}
else { currentPart += c; }
}
strParts.Add(currentPart); // Don't forget to add the last string
return strParts;
}
}
Note this is a very basic version that doesn't support complex interpolation parameters.. Only parameters that are field members of the class that is passed as 'context' will be supported.
You can expand the reflection parts to support propeties, methods, and references if you want.. or even direct code (math operations, etc).
I would highly recommend just using some IL instead, though.
I got an assignment where I have a few user inputs. My goal is that the user is only allowed to enter an integer. The program works as I want it to, but this message is messing with me.
What is the problem there, and how do I fix it?
static int Check_input(string input)
{
bool is_valid = Int32.TryParse(input, out int number);
if (is_valid)
{
number = 1;
}
else
{
number = 0;
}
return (number);
}
In the first line of your method bool is_valid = Int32.TryParse(input, out int number); you create a new variable number and assign a value to it. But you never use this value, because you immediately assign either the value 1 or 0 to it. Actually, you can shorten your code
static int Check_input(string input)
{
bool is_valid = Int32.TryParse(input, out _);
if (is_valid)
{
return 1;
}
else
{
return 0;
}
}
Here, you discard the out parameter of TryParse and only investigate its return value to check which value your method should return.
But actually, you should return a bool value to see whether the user entered a valid number, which would make your method look like this:
static bool Check_input(string input)
{
return Int32.TryParse(input, out _);
}
This is even simpler and it is easier to work with a boolean variable then with an integer that might be 1 or 0. Compare this:
if(Check_input("test") == 1)
{
Console.WriteLine("good input");
}
else
{
Console.WriteLine("bad input");
}
with
if(Check_input("test"))
{
Console.WriteLine("good input");
}
else
{
Console.WriteLine("bad input");
}
You wouldn't need to asign number with out int number, because you are setting it to 0 or 1 later anyway.
To be more accurate your if, else is useless anyway. You are already setting the number to either 1 or 0 or you wouldn't be able to set it equal to a bool anyway.
Fixed Code:
static bool Check_input(string input) {
bool is_valid = Int32.TryParse(input, out _);
return (is_valid);
}
How from switch to return result return?
Method1, depending on the value of the variable "str_1", selects an additional method to execute.
I get an error:
"Using local variable" s1 ", which is not assigned a value."
Code
public string Method1(string str_1)
{
string s1;
switch (str_1)
{
case "type_1":
s1 = MethodTest();
break;
}
return s1;
}
public string MethodTest()
{
string s = "test";
return s;
}
Thats correct. Switch not necessarily will lead to use your one case you have.
There are need to be performed one of 2 changes:
1)
string s1 = string.Empty; //(provide default value)
2) provide:
switch (str_1)
{
/*...*/
default:
s1 = "...";
break;
string s1 = string.Empty or string s1 = null
It is complaining that it's possible for that value to not be set since there isn't any guarantee that the switch-case statement will be hit.
s1 has the possibility to have never been set to a value. The error will go away if you while declaring your string, you set it equal to a default value:
string s1 = string.Empty;
I see 4 options:
1) string s1= string.Empty;
2) string s1= null;
3) string s1="";
4) You can make a small refactor:
public string Method1(string str_1)
{
switch (str_1)
{
case "type_1":
return MethodTest();
default:
return string.Empty;
}
}
You can avoid local variable. Just decide what are you going to return in default case.
public string Method1(string str_1)
{
switch (str_1)
{
case "type_1":
return MethodTest();
default:
return null;
}
}
I have to check the condition in asp.net for string array
The conditions is I can either have two values 360__image.jpg and image.jpg.
I have to return the correct value from the condition
If the string has 360_image.jpg I have to return only image.jpg and cutting 360_
If the string is image.jpg I have to return the same image.jpg
Code
public string splitString(string str)
{
string[] FileName = str.Split('_');
if (FileName[2] != "")
{
return FileName[2];
}
else
{
return FileName[0];
}
}
The problem with above code is I am getting the error
Index was outside the bounds of the array
You should check for length before accessing element from the array, that is why you are getting the exception, since split probably resulted in array of two elements.
Not exactly sure about your requirement but I think you can simplify your method as:
public string splitString(string str)
{
if (str.Contains("_")) //or check for 360__
return str.Substring(str.LastIndexOf('_') + 1);
else
return str;
}
You can use LastIndexOf:
public string splitString(string str)
{
return str.Substring(str.LastIndexOf('_') + 1);
}
Or even use LINQ Last:
public string splitString(string str)
{
return str.Split('_').Last();
}
Array has 2 elements , means idexes 0 and 1.
But you have taken into your code as FileName[2] .
This 2nd index may be wrong thats why error is comming. It may be 1.
Try with:
public string splitString(string str)
{
string[] FileName = str.Split('_');
if (FileName[1] != "")
{
return FileName[1];
}
else
{
return FileName[0];
}
}
I'd like to know on C# how to check if a string is a number (and just a number).
Example :
141241 Yes
232a23 No
12412a No
and so on...
Is there a specific function?
Look up double.TryParse() if you're talking about numbers like 1, -2 and 3.14159. Some others are suggesting int.TryParse(), but that will fail on decimals.
string candidate = "3.14159";
if (double.TryParse(candidate, out var parsedNumber))
{
// parsedNumber is a valid number!
}
EDIT: As Lukasz points out below, we should be mindful of the thread culture when parsing numbers with a decimal separator, i.e. do this to be safe:
double.TryParse(candidate, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var parsedNumber)
If you just want to check if a string is all digits (without being within a particular number range) you can use:
string test = "123";
bool allDigits = test.All(char.IsDigit);
Yes there is
int temp;
int.TryParse("141241", out temp) = true
int.TryParse("232a23", out temp) = false
int.TryParse("12412a", out temp) = false
Hope this helps.
Use Int32.TryParse()
int num;
bool isNum = Int32.TryParse("[string to test]", out num);
if (isNum)
{
//Is a Number
}
else
{
//Not a number
}
MSDN Reference
Use int.TryParse():
string input = "141241";
int ouput;
bool result = int.TryParse(input, out output);
result will be true if it was.
Yep - you can use the Visual Basic one in C#.It's all .NET; the VB functions IsNumeric, IsDate, etc are actually static methods of the Information class. So here's your code:
using Microsoft.VisualBasic;
...
Information.IsNumeric( object );
int value;
if (int.TryParse("your string", out value))
{
Console.WriteLine(value);
}
This is my personal favorite
private static bool IsItOnlyNumbers(string searchString)
{
return !String.IsNullOrEmpty(searchString) && searchString.All(char.IsDigit);
}
Perhaps you're looking for the int.TryParse function.
http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx
Many datatypes have a TryParse-method that will return true if it managed to successfully convert to that specific type, with the parsed value as an out-parameter.
In your case these might be of interest:
http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx
http://msdn.microsoft.com/en-us/library/system.decimal.tryparse.aspx
int result = 0;
bool isValidInt = int.TryParse("1234", out result);
//isValidInt should be true
//result is the integer 1234
Of course, you can check against other number types, like decimal or double.
You should use the TryParse method for the int
string text1 = "x";
int num1;
bool res = int.TryParse(text1, out num1);
if (res == false)
{
// String is not a number.
}
If you want to validate if each character is a digit and also return the character that is not a digit as part of the error message validation, then you can loop through each char.
string num = "123x";
foreach (char c in num.ToArray())
{
if (!Char.IsDigit(c))
{
Console.WriteLine("character " + c + " is not a number");
return;
}
}
int.TryPasrse() Methode is the best way
so if the value was string you will never have an exception , instead of the TryParse Methode return to you bool value so you will know if the parse operation succeeded or failed
string yourText = "2";
int num;
bool res = int.TryParse(yourText, out num);
if (res == true)
{
// the operation succeeded and you got the number in num parameter
}
else
{
// the operation failed
}
string str = "123";
int i = Int.Parse(str);
If str is a valid integer string then it will be converted to integer and stored in i other wise Exception occur.
Starting with C# 7.0, you can declare the out variable in the argument
list of the method call, rather than in a separate variable
declaration. This produces more compact, readable code, and also
prevents you from inadvertently assigning a value to the variable
before the method call.
bool isDouble = double.TryParse(yourString, out double result);
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier
You could use something like the following code:
string numbers = "numbers you want to check";
Regex regex = new Regex("^[0-9]+$"));
if (regex.IsMatch(numbers))
{
//string value is a number
}
public static void Main()
{
string id = "141241";
string id1 = "232a23";
string id2 = "12412a";
validation( id, id1, id2);
}
public static void validation(params object[] list)
{
string s = "";
int result;
string _Msg = "";
for (int i = 0; i < list.Length; i++)
{
s = (list[i].ToString());
if (string.IsNullOrEmpty(s))
{
_Msg = "Please Enter the value";
}
if (int.TryParse(s, out result))
{
_Msg = "Enter " + s.ToString() + ", value is Integer";
}
else
{
_Msg = "This is not Integer value ";
}
}
}
Try This
here i perform addition of no and concatenation of string
private void button1_Click(object sender, EventArgs e)
{
bool chk,chk1;
int chkq;
chk = int.TryParse(textBox1.Text, out chkq);
chk1 = int.TryParse(textBox2.Text, out chkq);
if (chk1 && chk)
{
double a = Convert.ToDouble(textBox1.Text);
double b = Convert.ToDouble(textBox2.Text);
double c = a + b;
textBox3.Text = Convert.ToString(c);
}
else
{
string f, d,s;
f = textBox1.Text;
d = textBox2.Text;
s = f + d;
textBox3.Text = s;
}
}
I'm not a programmer of particularly high skills, but when I needed to solve this, I chose what is probably a very non-elegant solution, but it suits my needs.
private bool IsValidNumber(string _checkString, string _checkType)
{
float _checkF;
int _checkI;
bool _result = false;
switch (_checkType)
{
case "int":
_result = int.TryParse(_checkString, out _checkI);
break;
case "float":
_result = Single.TryParse(_checkString, out _checkF);
break;
}
return _result;
}
I simply call this with something like:
if (IsValidNumber("1.2", "float")) etc...
It means that I can get a simple true/false answer back during If... Then comparisons, and that was the important factor for me. If I need to check for other types, then I add a variable, and a case statement as required.
use this
double num;
string candidate = "1";
if (double.TryParse(candidate, out num))
{
// It's a number!
}
int num;
bool isNumeric = int.TryParse("123", out num);
namespace Exception
{
class Program
{
static void Main(string[] args)
{
bool isNumeric;
int n;
do
{
Console.Write("Enter a number:");
isNumeric = int.TryParse(Console.ReadLine(), out n);
} while (isNumeric == false);
Console.WriteLine("Thanks for entering number" + n);
Console.Read();
}
}
}
Regex.IsMatch(stringToBeChecked, #"^\d+$")
Regex.IsMatch("141241", #"^\d+$") // True
Regex.IsMatch("232a23", #"^\d+$") // False
Regex.IsMatch("12412a", #"^\d+$") // False
The problem with some of the suggested solutions is that they don't take into account various float number formats. The following function does it:
public bool IsNumber(String value)
{
double d;
if (string.IsNullOrWhiteSpace(value))
return false;
else
return double.TryParse(value.Trim(), System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out d);
}
It assumes that the various float number styles such es decimal point (English) and decima comma (German) are all allowed. If that is not the case, change the number styles paramater. Note that Any does not include hex mumbers, because the type double does not support it.