Changing position of words in a string - c#

I have a string let say,
string temp1 = "25 10 2012"
but I want this,
"2012 10 25"
what would be the best way of doing it. format will always be like this.

Looks like its a date. You can parse the string to DateTime, using DateTime.ParseExact and then use .ToString to return formatted result.
DateTime dt = DateTime.ParseExact(temp1, "dd MM yyyy", CultureInfo.InvariantCulture);
Console.Write(dt.ToString("yyyy MM dd"));
You may use that DateTime object later in your code, and also apply different formatting (if you need)

try this split string and reverse array , and this will work for string of any length ...
string[] myArray = temp1.Split(' ');
Array.Reverse( myArray );
string reverse =string.Join(" ", myArray );

You could do it using the Split command and then recombining the sub strings:
String[] subStrs = temp1.Split( ' ' );
String final = subStrs[2] + " " + subStrs[1] + " " + subStrs[0];

So you want to split words and change the order, you can use LINQ:
var words = temp1.Split(' ');
String newWord = string.Join(" ", words.Reverse());
or if you don't want to swap all words but only swap the first and last word:
String first = words.Last();
String last = words.First();
String newWord = first + " "
+ string.Join(" ", words.Skip(1).Take(words.Length - 2))
+ " " + last;

You could either use a RegEx or split the string and rejoin it in reverse order.
string s = "2012 10 25";
string[] tokens = s.Split(' ');
Array.Reverse(tokens);
string final = string.Join(" ", tokens);

If Your string has always 10 character (with spaces), You can do the following:
string str = "26 10 2012"
str = str.Substring(6, 4) + " " + str.Substring(3, 2) + " " + str.Substring(0, 2)

you can use string.split(" ").reverse().join(" ").
You can use split, this function will split your string to array on white space as condition then reverse the array and re join based on white space
let string="25 10 2012";
let output=string.split(" ").reverse().join(" ");
console.log(output)

Related

How to find the second word in a string

When I run this code, it's purpose is to obtain the first, second, and third word in a 3 word sentence only and have each of those words display in a text box. The sentence I use is 'kerry tells stories', look at pic to see what I mean,
The problem however, is that when i run it, the third word is 'stori', what happened to 'es' making 'stories'
var tbt = textBox.Text;
var firstWord = tbt.Substring(0, tbt.IndexOf(" "));
var indexword = tbt.IndexOf(" ");
var indexnumber = indexword +1;
string myString = indexnumber.ToString();
var secondWord = tbt.Substring(indexnumber, tbt.IndexOf(" "));
var indexword2 = tbt.IndexOf(" ", indexnumber);
var indexnumber2 = indexword2 + 1;
string myString2 = indexnumber2.ToString();
var thirdWord = tbt.Substring(indexnumber2, tbt.IndexOf(" "));
var indexword3 = tbt.IndexOf(" ", indexnumber2);
var indexnumber3 = indexword3 + 1;
string mystring3 = indexnumber3.ToString();
textBox6.Text = firstWord;
textBox7.Text = secondWord;
textBox8.Text = thirdWord;
Where is the problem?
You can try splitting the sentence via String.Split() method:
string test = "kelly tell stories";
string[] split = test.Split(' '); //Use empty space between word(s) as split character
for(int i=0; i< split.Length; i++)
{
Console.WriteLine(split[i]);
}
Console.ReadLine();
This yields 3 string elements in one-dimensional array, each element can be accessed via index. 0 = first word, 1 = second word... so on.
Why make it too complicated ? can do it simply by the following code :
string input = "kerry tells stories";
string[] output=input.Split(' ');
textBox6.Text = output[0];
textBox7.Text = output[1];
textBox8.Text = output[2];
The IndexOf is using the index of the first space, it doesn't move across.
Reports the zero-based index of the first occurrence of the specified string in this instance.
You can do this much more simply by using Split
var words = tbt.Split(new char[]{' '});
1 = words[0]
2 = words[1]
3 = words[2]
Here is an approach using split with multiple tokens:
Dim a() As String = txtSource.Text.Split({vbCr, vbLf, ".", "?", "!"}, StringSplitOptions.RemoveEmptyEntries)
txtSentences.Text = String.Join(vbCrLf, a)
a = txtSource.Text.Split({" ", ",", ";", ":", vbCr, vbLf, ".", "?", "!"}, StringSplitOptions.RemoveEmptyEntries)
txtWords.Text = String.Join(vbCrLf, a)
Won't work with all cases, but a lot is them. Add three multiline textboxes to test: txtSource, txtSentences, TxtWords

how to count words correctly in text [duplicate]

This question already has answers here:
C# Word Count function
(5 answers)
Closed 8 years ago.
I want give my program a text and it count the words correctly
I tried to use an array to save words in it :
string[] words = richTextBox1.Text.Split(' ');
But this code has a problem and it is count the spaces in text
so I tried the following code :
string[] checkwords= richTextBox1.Text.Split(' ');
for (int i = 0; i < checkwords.Length; i++)
{
if (richTextBox1.Text.EndsWith(" ") )
{
return;
}
else
{
string[] words = richTextBox1.Text.Split(' ');
toolStripStatusLabel1.Text = "Words" + " = " + words.Length.ToString();
but now it wont work correctly .
I'd recommend using Regex here, using the 'word boundary' anchor
Otherwise your code may not correctly take into account things like Tabs and New Lines - \b will take care of that for you
var words = Regex
.Split("hello world", #"\b")
.Where(s => !string.IsNullOrWhiteSpace(s));
var wordCount = words.Count();
You can use the overload of String.Split with StringSplitOptions.RemoveEmptyEntries to ignore multiple consecutive spaces.
string text = "a b c d"; // 4 "words"
int words = text.Split(new char[]{}, StringSplitOptions.RemoveEmptyEntries).Length;
I'm using an empty char[] (you can also use new string[]{}) because that takes all white-space characters into account, so not only ' ' but also tabs or new-line characters.
I do not know why you wish to return if the textbox ends in " ". Maybe it should be a next or continue instead.
If multiple spaces is a possibility.
Regex myRege = new Regex(#"[ ]{2,}");
string myText = regex.Replace(richTextBox1.Text, #" ");
string[] words= myText.Split(" ");
toolStripStatusLabel1.Text = "Words" + " = " + words.Length.ToString();
Just for fun
private string[] GetCount(string bodyText)
{
bodyText = bodyText.Replace(" "," ");
if(bodyText.Contains(" ")
GetCount(bodyText)
return bodyText.Split(' ');
}
string[] words = GetCount(richTextBox1.Text)
toolStripStatusLabel1.Text = "Words" + " = " + words.Length.ToString();

Format string with regex in c#

I would like to format a string that looks like this
BPT4SH9R0XJ6
Into something that looks like this
BPT4-SH9R-0XJ6
The string will always be a mix of 12 letters and numbers
Any advice will be highly appreciated, thanks
Try Regex.Replace(input, #"(\w{4})(\w{4})(\w{4})", #"$1-$2-$3");
Regex is often derided, but is a pretty neat way of doing what you need. Can be extended to more complex requirements that are difficult to meet using string methods.
You can use "(.{4})(.{4})(.{4})" as your expression and "$1-$2-$3" as your replacement. This is, however, hardly a good use for regexp: you can do it much easier with Substring.
var res = s.Substring(0,4)+"-"+s.Substring(4,4)+"-"+s.Substring(8);
If the rule is to always split in three block of four characters no need for a reg exp:
str.Substring(0,4) + "-" + str.Substring(4,4) + "-" + str.Substring(8,4)
It would seem that a combination of String.Concat and string.Substring should take care of everything that you need.
var str = "BPT4SH9R0XJ6";
var newStr = str.Substring(0, 4) + "-" + str.Substring(4, 4) + "-" + str.Substring(8, 4);
Any reason you want to do a regex? you could just insert hyphens:
string s = "BPT4SH9R0XJ6";
for(int i = 4; i < s.length; i = i+5)
s = s.Insert(i, "-");
This would keep adding hyphens every 4 characters, would not error out if string was too short/long/etc.
return original_string.SubString(0,4)+"-"+original_string.SubString(4,4)+"-"+original_string.SubString(8,4);
string str = #"BPT4SH9R0XJ6";
string formattedString = string.Format("{0}-{1}-{2}", str.Substring(0, 4), str.Substring(4,4), str.Substring(8,4));
This works with any length of string:
for (int i = 0; i < (int)Math.Floor((myString.Length - 1) / 4d); i++)
{
myString = myString.Insert((i + 1) * 4 + i, "-");
}
Ended upp using this
var original = "BPT4SH9R0XJ6".ToCharArray();
var first = new string(original, 0, 4);
var second = new string(original, 4, 4);
var third = new string(original, 8, 4);
var mystring = string.Concat(first, "-", second, "-", third);
Thanks
If you are guaranteed the text you're operating on is the 12 character code then why don't you just use substring? Why do you need the Regex?
String theString = "AB12CD34EF56";
String theNewString = theString.Substring(0, 4) + "-" + theString.Substring(4, 4) + "-" + theString.Substring(8, 4);'

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;
}

How might I reformulate a "MM/YYYY" date as "YYYYMM"?

I want to convert this string format:
11/2013
TO
201311
So, suppose my string is in this variable:
string s = "11/2013";
What should be the code for this problem? Thanks!
sprime = s.Split(new char [] {'/'});
s = sprime[1] + sprime[0];
This is fastest:
s = s[3] + s[4] + s[5] + s[6] + s[0] + s[1];
If you are converting a gazillion billion records it will matter.
string newString = s.Split('/')[1] + s.Split('/')[0];
string [] split = s.Split('/');
string str = split[1] + split[0];
string s = "11/2011";
s = String.Format("{0}{1}", s.Split('/')[1], s.Split('/')[0]);
Note that this answer assumes s will match, and it will return an empty string if it doesn't.
Using Split will throw an IndexOutOfRangeException when you try to access [1] when there was no /.
You could of course add code to handle these cases regardless of whether you use Regex or Split.
string s = "11/2013";
// Match 1+ digits followed by a forward slash followed by 1+ digits
Regex r = new Regex(#"(\d+)/(\d+)");
var m = r.Match(s);
string result = m.Groups[2].Value + m.Groups[1].Value;
All so complicated. Makes my head hurt. Try this instead:
static readonly Regex rx = new Regex( #"^(\d\d)/(\d\d\d\d)$" ) ;
...
string s1 = "12/3456" ;
string s2 = rx.Replace( s1 , #"$2/$1" ) ;
Or Splitless for [??]/YYYY; s.Substring(s.Length - 4, 4) + s.Substring(0, s.Length - 5);
string s = "11/2013";
Regex r = new Regex("^(?<month>[0-1]?[0-9])/(?<year>[0-9]{4})$");
var match = r.Match(s);
string month = match.Groups["month"].Value;
string year = match.Groups["year"].Value;
string result = year + month;

Categories

Resources