can't convert simple list to string in unity - c#

This code works fine on wpf.
In my code list1 will work but if convert a string to a list of char and change again to string it showing error of : can't convert from char[] to string [].
need suggestion.
here's the code :
string x = "hello";
List<char> list = x.ToList<char>();
//error
string combindedString = string.Join(",", list.ToArray());
string xz = string.Join("", list);
//---
//okay....
List<string> list1 = new List<string>()
{
"Red",
"Blue",
"Green"
};
string output = string.Join("", list1.ToArray());
in wpf:

Well I suspect the source of your issue still lies with using the older .Net Framework that is default with Unity, 3.5 I believe. You have some options, to work around the problem though:
You can target an update framework, I believe Unity supports up to 4.6.1 in experimental mode.
You can work around converting a char[] to string.
Or just use the string constructor:
A simple example:
[Test]
public void StringTest()
{
string x = "hello";
List<char> list = x.ToList<char>();
string newStr = new string(list.ToArray());
Assert.IsTrue(newStr == x);
}

This can easily be achieved with a loop.
string x = "hello"
List<char> list = x.ToList<char>();
string originalword = "";
foreach (var letter in list)
{
originalword += letter.ToString();
}
// original word is equal to hello

Related

Best way to add delimeter betwen text in an array?

How can i add a symbol between the array of strings in this method? I tried using an if statement within the for each loop that added the symbol between each index of the array but it didn't work.
public string addSymbolBetweenStringArray(string[] strArray, string symbol)
{
string s = default(string);
foreach (string str in strArray)
{
}
return s;
}
string[] strArray = { "Hello", "World", };
string symbol = "-";
addSymbolBetweenStringArray(stringArray, symbol);
The method then returns Hello-World
You are looking for the string.Join method. For example:
string[] strArray = { "Hello", "World", };
string symbol = "-";
var output = string.Join(symbol, strArray);
You can use String.Join:
string result = String.Join(symbol, strArray);

How to make string list to "string array"

This is what I want to convernt: {"apple", "banana"} to "["apple", "banana"]"
I have tried convert string list to string array first, then convert string array to string, but did not work.
var testing = new List<string> {"apple", "banana"};
var arrayTesting = testing.ToArray();
var result = arrayTesting.ToString();
You can use string.Join(String, String[]) method like below to get a , separated string values (like csv format)
var stringifiedResult = string.Join(",", result);
You can try this, should work;
var testing = new List<string> { "apple", "banana" };
var arrayTesting = testing.ToArray<string>();
var result = string.Join(",", arrayTesting);
You can also use StringBuilder
StringBuilder sb = new StringBuilder();
sb.Append("\"[");
for (int i = 0; i < arrayTesting.Length; i++)
{
string item = arrayTesting[i];
sb.Append("\"");
sb.Append(item);
if (i == arrayTesting.Length - 1)
{
sb.Append("\"]");
}
else
sb.Append("\",");
}
Console.WriteLine(sb);
Instead of converting it to an array, you could use a linq operator on the list to write all the values into a string.
string temp = "";
testing.ForEach(x => temp += x + ", ");
This will leave you with a single string with each value in the list separated by a comma.

How do I check if a string contains a string from an array of strings?

So here is my example
string test = "Hello World, I am testing this string.";
string[] myWords = {"testing", "string"};
How do I check if the string test contains any of the following words? If it does contain how do I make it so that it can replace those words with a number of asterisks equal to the length of that?
You can use a regex:
public string AstrixSomeWords(string test)
{
Regex regex = new Regex(#"\b\w+\b");
return regex.Replace(test, AsterixWord);
}
private string AsterixWord(Match match)
{
string word = match.Groups[0].Value;
if (myWords.Contains(word))
return new String('*', word.Length);
else
return word;
}
I have checked the code and it seems to work as expected.
If the number of words in myWords is large you might consider using HashSet for better performance.
bool cont = false;
string test = "Hello World, I am testing this string.";
string[] myWords = { "testing", "string" };
foreach (string a in myWords)
{
if( test.Contains(a))
{
int no = a.Length;
test = test.Replace(a, new string('*', no));
}
}
var containsAny = myWords.Any(x => test.Contains(x));
Something like this
foreach (var word in mywords){
if(test.Contains(word )){
string astr = new string("*", word.Length);
test.Replace(word, astr);
}
}
EDIT: Refined

How to remove lowercase on a textbox?

I'm trying to remove the lower case letters on a TextBox..
For example, short alpha code representing the insurance (e.g., 'BCBS' for 'Blue Cross Blue Shield'):
txtDesc.text = "Blue Cross Blue Shield";
string Code = //This must be BCBS..
Is it possible? Please help me. Thanks!
Well you could use a regular expression to remove everything that wasn't capital A-Z:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main( string[] args )
{
string input = "Blue Cross Blue Shield 12356";
Regex regex = new Regex("[^A-Z]");
string output = regex.Replace(input, "");
Console.WriteLine(output);
}
}
Note that this would also remove any non-ASCII characters. An alternative regex would be:
Regex regex = new Regex(#"[^\p{Lu}]");
... I believe that should cover upper-case letters of all cultures.
string Code = new String(txtDesc.text.Where(c => IsUpper(c)).ToArray());
Here is my variant:
var input = "Blue Cross Blue Shield 12356";
var sb = new StringBuilder();
foreach (var ch in input) {
if (char.IsUpper(ch)) { // only keep uppercase
sb.Append(ch);
}
}
sb.ToString(); // "BCBS"
I normally like to use regular expressions, but I don't know how to select "only uppercase" in them without [A-Z] which will break badly on characters outside the English alphabet (even other Latin characters! :-/)
Happy coding.
But see Mr. Skeet's answer for the regex way ;-)
Without Regex:
string input = "Blue Cross Blue Shield";
string output = new string(input.Where(Char.IsUpper).ToArray());
Response.Write(output);
string Code = Regex.Replace(txtDesc.text, "[a-z]", "");
I´d map the value to your abbreviation in a dictionary like:
Dictionary<string, string> valueMap = new Dictionary<string, string>();
valueMap.Add("Blue Cross Blue Shield", "BCBS");
string Code = "";
if(valueMap.ContainsKey(txtDesc.Text))
Code = valueMap[txtDesc.Text];
else
// Handle
But if you still want the functionality you mention use linq:
string newString = new string(txtDesc.Text.Where(c => char.IsUpper(c).ToArray());
You can try use the 'Replace lowercase characters with star' implementation, but change '*' to '' (blank)
So the code would look something like this:
txtDesc.Text = "Blue Cross Blue Shield";
string TargetString = txt.Desc.Text;
string MainString = TargetString;
for (int i = 0; i < TargetString.Length; i++)
{
if (char.IsLower(TargetString[i]))
{
TargetString = TargetString.Replace( TargetString[ i ].ToString(), string.Empty );
}
}
Console.WriteLine("The string {0} has converted to {1}", MainString, TargetString);
string caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string.Join("",
"Blue Cross Blue Shield".Select(c => caps.IndexOf(c) > -1 ? c.ToString() : "")
.ToArray());
Rather than matching on all capitals, I think the specification would require matching the first character from all the words. This would allow for inconsitent input but still be reliable in the long run. For this reason, I suggest using the following code. It uses an aggregate on each Match from the Regex object and appends the value to a string object called output.
string input = "Blue Cross BLUE shield 12356";
Regex regex = new Regex("\\b\\w");
string output = regex.Matches(input).Cast<Match>().Aggregate("", (current, match) => current + match.Value);
Console.WriteLine(output.ToUpper()); // outputs BCBS1
string Code = Regex.Replace(txtDesc.text, "[a-z]", "");
This isn't perfect but should work (and passes your BCBS test):
private static string AlphaCode(String Input)
{
List<String> capLetter = new List<String>();
foreach (Char c in Input)
{
if (char.IsLetter(c))
{
String letter = c.ToString();
if (letter == letter.ToUpper()) { capLetter.Add(letter); }
}
}
return String.Join(String.Empty, capLetter.ToArray());
}
And this version will handle strange input scenarios (this makes sure the first letter of each word is capitalized).
private static string AlphaCode(String Input)
{
String capCase = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Input.ToString().ToLower());
List<String> capLetter = new List<String>();
foreach (Char c in capCase)
{
if (char.IsLetter(c))
{
String letter = c.ToString();
if (letter == letter.ToUpper()) { capLetter.Add(letter); }
}
}
return String.Join(String.Empty, capLetter.ToArray());
}

formatting string in MVC /C#

I have a string 731478718861993983 and I want to get this 73-1478-7188-6199-3983 using C#. How can I format it like this ?
Thanks.
By using regex:
public static string FormatTest1(string num)
{
string formatPattern = #"(\d{2})(\d{4})(\d{4})(\d{4})(\d{4})";
return Regex.Replace(num, formatPattern, "$1-$2-$3-$4-$5");
}
// test
string test = FormatTest1("731478718861993983");
// test result: 73-1478-7188-6199-3983
If you're dealing with a long number, you can use a NumberFormatInfo to format it:
First, define your NumberFormatInfo (you may want additional parameters, these are the basic 3):
NumberFormatInfo format = new NumberFormatInfo();
format.NumberGroupSeparator = "-";
format.NumberGroupSizes = new[] { 4 };
format.NumberDecimalDigits = 0;
Next, you can use it on your numbers:
long number = 731478718861993983;
string formatted = number.ToString("n", format);
Console.WriteLine(formatted);
After all, .Net has very good globalization support - you're better served using it!
string s = "731478718861993983"
var newString = (string.Format("{0:##-####-####-####-####}", Convert.ToInt64(s));
LINQ-only one-liner:
var str = "731478718861993983";
var result =
new string(
str.ToCharArray().
Reverse(). // So that it will go over string right-to-left
Select((c, i) => new { #char = c, group = i / 4}). // Keep group number
Reverse(). // Restore original order
GroupBy(t => t.group). // Now do the actual grouping
Aggregate("", (s, grouping) => "-" + new string(
grouping.
Select(gr => gr.#char).
ToArray())).
ToArray()).
Trim('-');
This can handle strings of arbitrary lenghs.
Simple (and naive) extension method :
class Program
{
static void Main(string[] args)
{
Console.WriteLine("731478718861993983".InsertChar("-", 4));
}
}
static class Ext
{
public static string InsertChar(this string str, string c, int i)
{
for (int j = str.Length - i; j >= 0; j -= i)
{
str = str.Insert(j, c);
}
return str;
}
}
If you're dealing strictly with a string, you can make a simple Regex.Replace, to capture each group of 4 digits:
string str = "731478718861993983";
str = Regex.Replace(str, "(?!^).{4}", "-$0" ,RegexOptions.RightToLeft);
Console.WriteLine(str);
Note the use of RegexOptions.RightToLeft, to start capturing from the right (so "12345" will be replaced to 1-2345, and not -12345), and the use of (?!^) to avoid adding a dash in the beginning.
You may want to capture only digits - a possible pattern then may be #"\B\d{4}".
string myString = 731478718861993983;
myString.Insert(2,"-");
myString.Insert(7,"-");
myString.Insert(13,"-");
myString.Insert(18,"-");
My first thought is:
String s = "731478718861993983";
s = s.Insert(3,"-");
s = s.Insert(8,"-");
s = s.Insert(13,"-");
s = s.Insert(18,"-");
(don't remember if index is zero-based, in which case you should use my values -1)
but there is probably some easier way to do this...
If the position of "-" is always the same then you can try
string s = "731478718861993983";
s = s.Insert(2, "-");
s = s.Insert(7, "-");
s = s.Insert(12, "-");
s = s.Insert(17, "-");
Here's how I'd do it; it'll only work if you're storing the numbers as something which isn't a string as they're not able to be used with format strings.
string numbers = "731478718861993983";
string formattedNumbers = String.Format("{0:##-####-####-####-####}", long.Parse(numbers));
Edit: amended code, since you said they were held as a string in your your original question

Categories