I have a string that looks like a phone number. I'm using a lambda to extract an array of char. Then I want to convert this array into a string. This is what I have:
PhoneCandidate = "(123)-321-1234"; //this is just an example of what it could look like
var p = PhoneCandidate.Where(c => char.IsDigit(c)).ToArray();
string PhoneNumber = p.toString();
However, when I run this code, the variable PhoneNumber becomes just "System.Char[]" instead of the values inside the array.
What do I need to change?
Thanks.
You can use the string constructor that takes a char[].
string PhoneNumber = new string(p);
string phone = new string(p);
Try with constructor res = new string(yourArray);
One of the string constructors takes a char[]:
string PhoneNumber = new string(p);
Let's take this a whole new direction:
Dim digits as New Regex(#"\d");
string phoneNumber = digits.Replace(PhoneCandidate, "");
Assuming p is a char[] you can use the following:
String phoneNumber = new String(p);
probably the best bet is to use the string constructor per (#Adam Robinson) however as an alternative, you can also use string.Join(string separator,params string[] value)
(MSDN docs here)
PhoneCandidate = "(123)-321-1234"; //this is just an example of what it could look like
var p = PhoneCandidate.Where(c => char.IsDigit(c)).ToArray();
string str = string.Join(string.Empty,p);
Related
I've the following string that I get from a method. I would like to parse it and make pairs. The order of input string will not change.
INPUT:
ku=value1,ku=value2,ku=value3,ku=value4,ku=value5,lu=value6,lu=value7,lu=value8,lu=value9
OUTPUT
Name value1
Title value2
School value3
.
.
.
Age value9
I think I can read through the string and assign value to the left hand side as I go and so on. However, I am very new to C#.
Use string.Split and split imput string to list key-value pair then split each pair to key and value. Tahts all.
You can do something like this:
void Main()
{
string str = "ku=value1,ku=value2,ku=value3,ku=value4,ku=value5,lu=value6,lu=value7,lu=value8,lu=value9";
var tempStr = str.Split(',');
var result = new List<KeyValue>();
foreach(var val in tempStr)
{
var temp = val.Split('=');
var kv = new KeyValue();
kv.Name = temp[0];
kv.Value = temp[1];
result.Add(kv);
}
}
public class KeyValue
{
public string Name {get;set;}
public string Value{get;set;}
}
If you don't need the first part you can do this using String split as follow
Split String on , using String.Split method creating sequence of string {"ku=value1","ku=value2",...}
Use Linq's Select method to apply an additional transformation
Use Split again on each item on the '=' character
Select the item to the right of the '=', at index 1 of the newly split item
Loop through everything and print your results
Here's the code
var target = "ku=value1,ku=value2,ku=value3,ku=value4,ku=value5,lu=value6,lu=value7,lu=value8,lu=value9";
var split = target.Split(',').Select(a=>a.Split('=')[1]).ToArray();
var names = new[]{"Name","Title","School",...,"Age"};
for(int i=0;i<split.Length;i++)
{
Console.WriteLine(names[i]+"\t"+split[i]);
}
If you want to find out more about how to use these methods you can look at the MSDN documentation for them :
String.Split(char[]) Method
Enumerable.Select Method
I suggest to try this way. Split() plus regular expression
string inputString = "ku=value1,ku=value2,ku=value3,ku=value4,ku=value5,lu=value6,lu=value7,lu=value8,lu=value9";
string pattern = "(.*)=(.*)";
foreach(var pair in inputString.Split(','))
{
var match = Regex.Match(pair,pattern);
Console.WriteLine(string.Format("{0} {1}",match.Groups[1].Value, match.Groups[2].Value));
}
I'm getting pretty frustrated with this, and hope the community can help me out.
I have a string, an example would be "1_ks_Males", another example would be "12_ks_Females".
What I need to do is write a method that extract's each value. So from the first example I'd want something like this:
1
ks
Males
In separate variables.
I'm sure I'm just being incredibly thick, but I just can't get it!
Simply use string.Split('_'). With your input strings it will return a string array with three elements.
You can use Split function for String. Something like this
var split = "1_ks_Males".Split('_');
var first = split[0];
var second = split[1];
var third = split[2];
You just need to use split:
var exampleString = "1_ks_Males";
var split = exampleString.split("_");
var first= split[0]; // 1
var second = split[1]; // ks
var third = split[2]; // Males
string[] array = "1_ks_Males".Split('_');
Assert.AreEqual("1",array[0])
Assert.AreEqual("ks",array[1])
Assert.AreEqual("Males",array[2])
var values = "1_ks_Males".Split('_');
// values[0]: 1
// values[1]: ks
// values[2]: Males
How about this?
var data = myString.Split("_");
var value = data[0];
var #type = data[1];
var gender = data[2];
use String.Split which returns an array of values
var values = "12_ks_Females".split("_");
// values[0] == "12"
// values[1] == "ks"
// values[2] == "Females"
You could use split -
var s = "1_ks_Males";
string[] values = s.Split('_');
Your values will then be contained in the `values' array -
var firstvalue = values[0];
var secondvalue = values[1];
var thirdvalue = values[2];
You'll want to look into the String.Split method of the String class. Here's the MSDN link.
Basically, if all of your strings have the values that you require separated by a consistent character (in your example, this is an underscore character), you can use the Split method which will split a single string into an array of new strings based upon a specific separator.
For example:
string s = "1_ks_Males";
string[] v = s.Split('_');
Console.WriteLine(v[0]);
Console.WriteLine(v[1]);
Console.WriteLine(v[2]);
would output:
1
ks
Males
You should use the String.Split method.
Like: string[] splitParts = "1_ks_Males".Split('_');
This should do the trick:
var values = myString.Split('_');
var splitVar = "1_ks_Males".Split('_');
var firstVar = splitVar[0];
var secondVar = splitVar[1];
var thirdVar = splitVar[2];
Use Split function of the string for it:
var variables = "1_ks_Males".Split(new char[]{'_'}, StringSplitOptions.IgnoreEmpty);
Now variables[0] == "1", variables[1] == "ks", and variables[2] == "Males"
You can use Split function provided by String. Read more about it # MSDN
var data = "1_ks_Males".Split('_');
If i am using C# and i have a string coming in from a database like this:
\RBsDC\1031\2011\12\40\1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA54E7CF517B2863E.XML
And i only want this part of the string:
1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA54E7CF517B2863E.XML
How can i get this string if there is more than one "\" symbol?
You can use the LastIndexOf() method of the String class:
string s = #"\RBsDC\1031\2011\12\40\1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA.xml";
Console.Out.WriteLine(s.Substring(s.LastIndexOf('\\') + 1));
Hope, this helps.
Use String.Split to split string by parts and then get the last part.
Using LINQ Enumerable.Last() :
text.Split('\\').Last();
or
// todo: add null-empty checks, etcs
var parts = text.Split('\\');
strign lastPart = parts[parts.Length - 1];
You can use a combination of String.LastIndexOf("\") and String.Substring(lastIndex+1). You could also use (only in the sample you provided) Path.GetFileName(theString).
string[] x= line.Split('\');
string goal =x[x.Length-1];
but linq will be easier
You can use regex or split the string by "\" symbol and take the last element of array
using System.Linq;
public class Class1
{
public Class1()
{
string s =
#"\RBsDC\1031\2011\12\40\1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA54E7CF517B2863E.XML";
var array = s.Split('\\');
string value = array.Last();
}
}
newstring = string.Substring(string.LastIndexOf(#"\")+1);
It seems like original string is like filePath.
This could be one easy solution.
string file = #"\RBsDC\1031\2011\12\40\1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA.xml";
string name = System.IO.Path.GetFileName(file);
When I need to print "00000", I can use "0"*5 in python. Is there equivalent in C# without looping?
Based on your example I figure you're going to be using these strings to help zero-pad some numbers. If that's the case, it would be easier to use the String.PadLeft() method to do your padding. You could be using the similar function in python as well, rjust().
e.g.,
var str = "5";
var padded = str.PadLeft(8, '0'); // pad the string to 8 characters, filling in '0's
// padded = "00000005"
Otherwise if you need a repeated sequence of strings, you'd want to use the String.Concat() method in conjunction with the Enumerable.Repeat() method. Using the string constructor only allows repetition of a single character.
e.g.,
var chr = '0';
var repeatedChr = new String(chr, 8);
// repeatedChr = "00000000";
var str = "ha";
// var repeatedStr = new String(str, 5); // error, no equivalent
var repeated = String.Concat(Enumerable.Repeat(str, 5));
// repeated = "hahahahaha"
One of the String ctor overloads will do this for you:
string zeros = new String('0', 5);
To add to the other answers, you won't be able to use this string constructor with another string to repeat strings, such as string s = new string("O", 5);. This only works with chars.
However, you can use Enumerable.Repeat() after adding using System.Linq; to achieve the desired result with strings.
string s = string.Concat(Enumerable.Repeat("O", 5));
Use
string s = new string( '0', 5 );
Found here
Depending on your application, this may be useful too:
int n = 0;
string s = n.ToString().PadRight(5, '0');
Don't ever, ever use this: string.Join("0", new string[6]);
Why not just "00000" ?! ducks
This one only works with zero: 0.ToString("D5");
I have a string like "3.9" I want to convert this string in to a number without using split function.
If string is 3.9 => o/p 39
If string is 1.2.3 => o/p 123
I'm not sure what the purpose is. Would it work for your case to just remove the periods and parse the number?
int result = Int32.Parse(str.Replace(".", String.Empty));
You could remove replace the . with empty string before trying to parse it:
string inputString = "1.2.3";
int number = int.Parse(inputString.Replace(".", ""));
string str = "3.9";
str = str.Replace(".","");
int i;
int.TryParse(str, out i);
I would probably go with something like this:
string str = "3.2";
str = str.Replace(".", "");
double number = convert.ToDouble(str);
you can use Replace(".",""); for this purpose
eg:
string stnumber= "5.9.2.5";
int number = Convert.ToInt32(stnumber.Replace(".", ""));
i think Convert.ToInt32(); is better than int.Parse();