How to find the second word in a string - c#

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

Related

How do i replace first letter in each word in a string?

string str = "ghy saste mater"
How do I replace first letter in each word from str to the letter "w"?
So the new string would be:
"why waste water"
How can I achieve this?
You would explode string.Split() your string using the delimeter of " " this would give you an array of strings and then you can loop over the entire array and call:
string.Replace(string[0], 'w')
A far more impressive manner of doing this would be using Regex.Replace() and writing a Regex to find the combination of a space and a character and then replace that string with a space and a w.
something like " a" would be replaced with " w"
This is really straitforward so I only provided some hints. Look-up what I talked about here and you'll be fine.
Try this :
string str = "ghy saste mater";
string[] parts = str.Split(' ');
string result = string.Join(" ", parts.Select(p => "w" + (p.Length > 1 ? p.Substring(1, p.Length - 1) : "")).ToArray());
You could split the string into an array and then change the first character in each element of the new array.
Something like:
string[] str_array = str.Split(' ');
for (int i = 0; i < str_array.Length; i++) {
str_array[i] = "w" + str_array[i].Substring(1, str_array[i].Length);
}
Then you would have to turn the array back into a string.
A neat way is to use Regex.Replace():
string str = "ghy saste mater";
var strModified = Regex.Replace(str, #"\b\w", "w");
You also could use LINQ:
var str = "ghy saste mater"
var strModified = string.Join(" ", str.Split().Select(s => "w" + s.Substring(1, s.Length - 1))));
If you modify strings a lot, consider using StringBuilder class:
var str = "ghy saste mater"
var strModified = str.Split().Select(s => "w" + s.Substring(1, s.Length - 1)).
Aggregate(new StringBuilder(), (b, s) => b.Append(s + " ")).ToString();
Just iterate through it.
string o = "";
o += str[0]
for (int i = 1; i < str.length; i++){
o+=str[i-1] == ' ' ? 'w' : str[i];
}

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();

Alternatively upper- and lowercase words in a string

I use Visual Studio 2010 ver.
I have array strings [] = { "eat and go"};
I display it with foreach
I wanna convert strings like this : EAT and GO
Here my code:
Console.Write( myString.First().ToString().ToUpper() + String.Join("",myString].Skip(1)).ToLower()+ "\n");
But the output is : Eat and go . :D lol
Could you help me? I would appreciate it. Thanks
While .ToUpper() will convert a string to its upper case equivalent, calling .First() on a string object actually returns the first element of the string (since it's effectively a char[] under the hood). First() is actually exposed as a LINQ extension method and works on any collection type.
As with many string handling functions, there are a number of ways to handle it, and this is my approach. Obviously you'll need to validate value to ensure it's being given a long enough string.
using System.Text;
public string CapitalizeFirstAndLast(string value)
{
string[] words = value.Split(' '); // break into individual words
StringBuilder result = new StringBuilder();
// Add the first word capitalized
result.Append(words[0].ToUpper());
// Add everything else
for (int i = 1; i < words.Length - 1; i++)
result.Append(words[i]);
// Add the last word capitalized
result.Append(words[words.Length - 1].ToUpper());
return result.ToString();
}
If it's always gonna be a 3 words string, the you can simply do it like this:
string[] mystring = {"eat and go", "fast and slow"};
foreach (var s in mystring)
{
string[] toUpperLower = s.Split(' ');
Console.Write(toUpperLower.First().ToUpper() + " " + toUpperLower[1].ToLower() +" " + toUpperLower.Last().ToUpper());
}
If you want to continuously alternate, you can do the following:
private static string alternateCase( string phrase )
{
String[] words = phrase.split(" ");
StringBuilder builder = new StringBuilder();
//create a flag that keeps track of the case change
book upperToggle = true;
//loops through the words
for(into i = 0; i < words.length; i++)
{
if(upperToggle)
//converts to upper if flag is true
words[i] = words[i].ToUpper();
else
//converts to lower if flag is false
words[i] = words[i].ToLower();
upperToggle = !upperToggle;
//adds the words to the string builder
builder.append(words[i]);
}
//returns the new string
return builder.ToString();
}
Quickie using ScriptCS:
scriptcs (ctrl-c to exit)
> var input = "Eat and go";
> var words = input.Split(' ');
> var result = string.Join(" ", words.Select((s, i) => i % 2 == 0 ? s.ToUpperInvariant() : s.ToLowerInvariant()));
> result
"EAT and GO"

How to parse a text removing a char

Let's start with that i have a txtProbe(textbox) and there i have 12-34-56-78-90. I want to parse them in different labels or textboxes ... For now just in one textbox - txtParse. I tried with that code - I'm removing the "-" and then tried to display them but nothing happens:
{
char[] delemiterChars = { '-' };
string text = txtProbe.Text;
string[] words = text.Split(delemiterChars);
txtParse.Text = text;
foreach (string s in words)
{
txtParse.Text = s;
}
}
EDIT:
I want to set the received information in different labels:
12-label1
34-label2
56-label3
78-label4
90-label5
You could just use String.Replace:
txtParse.Text = txtProbe.Text.Replace("-", " ");
The following 'll do the trick more "semantically":
var parsed = text.Replace("-", " ");
You might be changing the value too early in the Page Life Cycle (in the case of Web Forms), with regards to why you're not seeing the parsed value in the server control.
For your specific sample it seems that you could just replace '-' by ' '.
txtParse.Text = txtProbe.Text.Replace('-', ' ');
But in order to join an array of strings using a white space separator, you could use this
txtParse.Text = string.Join(" ", words);
Your logic is not appropiated for the task you're trying to acheive but just for learning purposes I'll write the correct version of your snippet
string separator = string.Empty; // starts empty so doesn't apply for first element
foreach (string s in words)
{
txtParse.Text += separator + s; // You need to use += operator to append content
separator = " "; // from second element will append " "
}
EDIT
This is for the case of using different labels
Label[] labelList = new Label[] {label1, label2, label3, label4, label5};
for (int i = 0; i < words.Length; i++)
{
labelList[i].Text = words[i];
}
You can use String.Join to join collection of strings as you want. In your case:
txtParse.Text = String.Join(" ", words);
You can use the delimiter character directly in .split('-') to return an array of strings representing that data you want.
Your problem is that you keep assigning s to the Text property. The end result will be the last s in your array.
You can use TextBox.AppendText() instead.
char[] delemiterChars = { '-' };
string text = txtProbe.Text;
string[] words = text.Split(delemiterChars);
txtParse.Text = text;
foreach (string s in words)
{
txtParse.AppendText(s + " ");
}
You can just put txtParse.Text = txtProbe.Text.Replace('-', " ");
Or by modifying your code:
char[] delemiterChars = { '-' };
string text = txtProbe.Text;
string[] words = text.Split(delemiterChars,StringSplitOptions.RemoveEmptyEntries);
foreach (string s in words)
{
txtParse.Text += " " + s;
}

How do i add a string after text if it's not already there?

How can i add a string after text if the string is not already there?
I have a textbox with the following lines:
name:username thumbnail:example.com message:hello
name:username message:hi
name:username message:hey
how can i add thumbnail:example.com after name:username to the second and third line but not the first line?
Edit: Didn't notice that you are reading from a textbox - you'll have to join the textbox lines to one string to use my example. You can do that with string.join()
Try this... this assumes that there are no spaces allowed in the username. There are probably plenty of better/more efficient ways to do this, but this should work.
var sbOut = new StringBuilder();
var combined = String.Join(Environment.NewLine, textbox1.Lines);
//split string on "name:" rather than on lines
string[] lines = combined.Split(new string[] { "name:" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in lines)
{
//add name back in as split strips it out
sbOut.Append("name:");
//find first space
var found = item.IndexOf(" ");
//add username IMPORTANT assumes no spaces in username
sbOut.Append(item.Substring(0, found + 1));
//Add thumbnail:example.com if it doesn't exist
if (!item.Substring(found + 1).StartsWith("thumbnail:example.com"))
sbOut.Append("thumbnail:example.com ");
//Add the rest of the string
sbOut.Append(item.Substring(found + 1));
}
var lines = textbox.Text.Split(new string[] { Environment.NewLine.ToString() }, StringSplitOptions.RemoveEmptyEntries);
textbox.Text = string.Empty;
for (int i = 0; i < lines.Length; i++)
{
if (!lines[i].Contains("thumbnail:example.com") && lines[i].Contains("name:"))
{
lines[i] = lines[i].Insert(lines[i].IndexOf(' '), " thumbnail:example.com");
}
}
textbox.Text = string.Join(Environment.NewLine, lines);
Hope this helps.

Categories

Resources