I have a string that looks something like this
Say_Hi~~~Say_Opt1~~Say_Opt3~~~Say_Opt6~~~Say_Opt9~~Say_GoodBye
It has 16 '~' dividing it into 17 "sections". In section number 5, I need to insert Say_Opt5.
Say_Hi~~~Say_Opt1~~Say_Opt3~~Say_Opt5~Say_Opt6~~~Say_Opt9~~Say_GoodBye
So I need to be able to take a string, and a position, and isert the string into the position specified. I tried using a regex but im not entire sure how matches work.
string baseString = "Say_Hi~~~Say_Opt1~~Say_Opt3~~~Say_Opt6~~~Say_Opt9~~Say_GoodBye";
var newString = new Regex("~").Replace(baseString, "Say_Opt5", 7);
Also, there may already be an Option 5, so I need to replace the old option5 with the new option 5. Such as replacing
Say_Hi~~~Say_Opt1~~Say_Opt3~~Say_Opt5~Say_Opt6~~~Say_Opt9~~Say_GoodBye
with
Say_Hi~~~Say_Opt1~~Say_Opt3~~Say_Opt5_Custom~Say_Opt6~~~Say_Opt9~~Say_GoodBye
var s1 = "there~is~a~~cat";
var s2 = "super";
var words = s1.Split('~').ToList();
//words.Insert(3, s2); // this will insert new token
words[3] = s2; // this will replace word at specific index
var res = string.Join("~", words.ToArray());
After this your cat will become a super hero, it will become a super cat :)
If you are using C#, you can use this:
string s = "Say_Hi~~~Say_Opt1~~Say_Opt3~~~Say_Opt6~~~Say_Opt9~~Say_GoodBye";
MessageBox.Show(s);
string[] parts = s.Split('~');
parts[YourIntegerIndex] = "YouNewString";
s = string.Join("~", parts);
MessageBox.Show(s);
Related
I want to get the value of the first white-space, from the right of a random string as below.
if my
1. string = "sdsd sdsd sdsd 3232323"
or
2. string = "sdsd sdsd dseee3232323"
or
3.string = "sdsd dseee3232323"
or
4.string = "sdsd dseee3232323"
output :
1. 3232323
2. dseee3232323
3. dseee3232323
4. dseee3232323
LastIndexOf method:
string s = "sdsd sdsd sdsd 3232323";
var result = s.Substring(s.LastIndexOf(' ') + 1);
Use Split and LastOrDefault, just like this:
var result = s.Split(' ').LastOrDefault();
Just don't forget to add the following to your using directives first:
using System.Linq;
Linq is not necessary.
String result = "";
String[] tempArray = workString.Split(' ');
if (tempArray.Length > 1)
String result = temparray[tempArray.Length-1];
Split into an array and look at the last element. I don't recommend using linq until you learn the basics.
Also I added a check to see if the result was invalid (no space). If you don't have a space, the other answers will return the entire string.
I know this question would have been asked infinite number of times, but I'm kinda stuck.
I have a string something like
"Doc1;Doc2;Doc3;12"
it can be something like
"Doc1;Doc2;Doc3;Doc4;Doc5;56"
Its like few pieces of strings separated by semicolon, followed by a number or id.
I need to extract the number/id and the strings separately.
To be exact, I can have 2 strings: one having "Doc1;Doc2;Doc3" or "Doc1;Doc2;Doc3;Doc4" and the other having just the number/id as "12" or "34" or "45" etc.
And yeah I am using C# 3.5
I understand its a pretty easy and witty question, but this guy is stuck.
Assistance required from experts.
Regards
Anurag
string.LastIndexOf and string.Substring are the keys to what you're trying to do.
var str = "Doc1;Doc2;Doc3;12";
var ind = str.LastIndexOf(';');
var str1 = str.Substring(0, ind);
var str2 = str.Substring(ind+1);
One way:
string[] tokens = str.Split(';');
var docs = tokens.Where(s => s.StartsWith("Doc", StringComparison.OrdinalIgnoreCase));
var numbers = tokens.Where(s => s.All(Char.IsDigit));
String docs = s.Substring(0, s.LastIndexOf(';'));
String number = s.Substring(s.LastIndexOf(';') + 1);
One possible approach would be this:
var ids = new List<string>();
var nums = new List<string>();
foreach (var s in input.Split(';'))
{
int val;
if (!int.TryParse(s, out val)) { ids.Add(s); }
else { nums.Add(s); }
}
where input is something like Doc1;Doc2;Doc3;Doc4;Doc5;56. Now, ids will house all of the Doc1 like values and nums will house all of the 56 like values.
you can use StringTokenizer functionality.
http://www.c-sharpcorner.com/UploadFile/pseabury/JavaLikeStringTokenizer11232005015829AM/JavaLikeStringTokenizer.aspx
split string using ";"
StringTokenizer st = new StringTokenizer(src1,";");
collect final String. that will be your ID.
You may try one of two options: (assuming your input string is in string str;
Approach 1
Get LastIndexOf(';')
Split the string based on the index. This will give you string and int part.
Split the string part and process it
Process the int part
Approach 2
Split the string on ;
Run a for loop - for (int i = 0; i < str.length - 2; i++) - this is the string part
Process str[length - 1] separately - this is the int part
Please take this as a starting point as there could be other approaches to implement a solution for this
string actual = "Doc1;Doc2;Doc3;12";
int lstindex = actual.LastIndexOf(';');
string strvalue = actual.Substring(0, lstindex);
string id = actual.Substring(lstindex + 1);
I need to locate a specific part of a string value like the one below, I need to alter the "Meeting ID" to a specific number.
This number comes from a dropdownlist of multiple numbers, so I cant simply use find & replace. As the text could change to one of multiple numbers before the user is happy.
The "0783," part of the string never changes, and "Meeting ID" is always followed by a ",".
So i need to get to "0783, INSERT TEXT ," and then insert the new number on the Index Changed event.
Here is an example :-
Business Invitation, start time, M Problem, 518-06-xxx, 9999 999
0783, Meeting ID, xxx ??
What is the best way of locating this string and replacing the test each time?
I hope this makes sense guys?
Okay, so there are several ways of doing this, however this seems to be a string you have control over so I'm going to say here's what you want to do.
var myString = string.Format("Business Invitation, start time, M Problem, 518-06-xxx, 9999 999 0783, {0}, xxx ??", yourMeetingId);
If you don't have control over it then you're going to have to be a bit more clever:
var startingIndex = myString.IndexOf("0783, ");
var endingIndex = myString.IndexOf(",", startingIndex + 6);
var pattern = myString.Substring(startingIndex + 6, endingIndex - (startingIndex + 6));
myString = myString.Replace(pattern, yourMeetingId);
You should store your "current" Meeting ID in a variable, changing it along with your user's actions, and then use that same global variable whenever you need the string.
This way, you don't have to worry about what's inside the string and don't need to mess with array indexes. You will also be safe from magic numbers / strings, which are bound to blow up in your face at some point in the future.
You can try with Regex.Replace method
string pattern = #"\d{3},";
Regex regex = new Regex(pattern);
var inputStr = "518-06-xxx, 9999 999 0783";
var replace = "..."
var outputStr = regex.Replace(inputStr, replace);
use Regex.Split by token "0783," then in the second string in the array return split by token "," the first element in the string array would be where you would insert new text. Then use string.Join to join the first split with "0783," and the join the second with ",".
string temp = "Business Invitation, start time, M Problem, 518-06-xxx, 9999 999 0783, Meeting ID, xxx ??";
string newID = "1234";
string[] firstSplits = Regex.Split(temp, "0783,");
string[] secondSplits = Regex.Split(firstSplits[1], ",");
secondSplits[0] = newID;
string #join = string.Join(",", secondSplits);
firstSplits[1] = #join;
string newString = string.Join("0783,", firstSplits);
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('_');
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");