Jump to content

c# Questions on dividing strings to substrings

Dravinian

Hey all,

 

For clarity, I am very new to c# programming, learning while working on a project as I find that is the best way to learn.  I have hit a bit of a bump in a part of hte project that I have been unable to find an answer that I could understand...


I have a long string, I can't say that the string will be an exact length in letters each time, but it will have a space as a delimiter between each word.  So no chance of AB requiring a substring for each letter.

 

My string would look like this:

 

Today Tomorrow Monday Tuesday Weekend January Wednesday Thursday Friday Saturday February March April etc. (length 18 words)

 

I want just the days of the week from the string.

 

The days will always be the 3rd, 4th, 8th, 9th and 10th words, and the string will always contain 18 words in total.

 

Now it may be that pulling out the 3rd, 4th, 8th, 9th and 10th words and ignoring the rest will suffice for my purposes.

 

I just need to deal with each day of the week separately rather than as a group so will need a unique identifier for each word.

 

Any assistance is greatly appreciated.

Link to comment
Share on other sites

Link to post
Share on other sites

4 minutes ago, Dravinian said:

My string would look like this:


Today Tomorrow Monday Tuesday Weekend January Wednesday Thursday Friday Saturday February March April etc. (length 18 words)

I want just the days of the week from the string.

The days will always be the 3rd, 4th, 8th, 9th and 10th words, and the string will always contain 18 words in total.

Now it may be that pulling out the 3rd, 4th, 8th, 9th and 10th words and ignoring the rest will suffice for my purposes.

I just need to deal with each day of the week separately rather than as a group so will need a unique identifier for each word.

I'm sort of confused by your implementation and use of this string here.

What I think you could be looking for is this:

string[] words = yourString.Split(" ");

This makes an array, by taking your string and splitting it (it splits on a whitespace). Now you can call the 3rd, 4th, 8th, 9th and 10th words in this array (your days of the week) like this:

// Keep in mind an array calls an object by its index. The index starts at 0, not at one (thus the first word in the array is words[0], second word is words[1], etc.)
string mondayString = words[2];
string tuesdayString = words[3];
// etc.

 

Although again, I am somewhat confused by your implementation of this string and your usage of it.

If you can give a bit more detail, I could maybe come up with a better answer.

"We're all in this together, might as well be friends" Tom, Toonami.

 

mini eLiXiVy: my open source 65% mechanical PCB, a build log, PCB anatomy and discussing open source licenses: https://linustechtips.com/topic/1366493-elixivy-a-65-mechanical-keyboard-build-log-pcb-anatomy-and-how-i-open-sourced-this-project/

 

mini_cardboard: a 4% keyboard build log and how keyboards workhttps://linustechtips.com/topic/1328547-mini_cardboard-a-4-keyboard-build-log-and-how-keyboards-work/

Link to comment
Share on other sites

Link to post
Share on other sites

3 minutes ago, minibois said:

I'm sort of confused by your implementation and use of this string here.

What I think you could be looking for is this:


string[] words = yourString.Split(" ");

This makes an array, by taking your string and splitting it (it splits on a whitespace). Now you can call the 3rd, 4th, 8th, 9th and 10th words in this array (your days of the week) like this:


// Keep in mind an array calls an object by its index. The index starts at 0, not at one (thus the first word in the array is words[0], second word is words[1], etc.)
string mondayString = words[2];
string tuesdayString = words[3];
// etc.

 

Although again, I am somewhat confused by your implementation of this string and your usage of it.

If you can give a bit more detail, I could maybe come up with a better answer.

Hi, I had got as far as .split.

 

What I did not know, is this created an array.  That had not come up in my research.

 

My implementation is a spreadsheet with 18 words in a list, from that spreadsheet (where the Row will be copied into an application) I want to take the 3rd, 4th, 8th, 9th and 10th words each time.  The rest of the words I don't need.

 

If it does in fact create an array, and string mondayString = words[3] will pull out the 3rd word in the longer string, then I think you have answered my question.

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, Dravinian said:

Hi, I had got as far as .split.

What I did not know, is this created an array.  That had not come up in my research.

With C#, Microsoft's documentation is the best source there is. For example, with String.split they give this is a brief explanation:

Quote

Returns a string array that contains the substrings in this instance that are delimited by elements of a specified string or Unicode character array.

https://docs.microsoft.com/en-us/dotnet/api/system.string.split?view=netcore-3.1

It also gives some relevant examples on how to use the function. Very helpful source for anything C# related!

3 minutes ago, Dravinian said:

My implementation is a spreadsheet with 18 words in a list, from that spreadsheet (where the Row will be copied into an application) I want to take the 3rd, 4th, 8th, 9th and 10th words each time.  The rest of the words I don't need.

If you already know you just want the names of the days of the week, it's better to just make a list of these names at the start of the program. No need to import a string, split it up, pick up a couple words, etc. really.

But if you don't know the data will always be that, it might be worth it to do it that way.

5 minutes ago, Dravinian said:

If it does in fact create an array, and string mondayString = words[3] will pull out the 3rd word in the longer string, then I think you have answered my question.

Yea, that's basically it. 

Get the string > split it > pick out the word(s) you need.

 

But keep in mind, an array starts at 0.

That means words[0] will pick the first word in the array and words[3] will pick out the fourth word in the array for example.

Just something to think about when working with arrays (or really any type of collection, like Lists, Dictionaries, etc.).

"We're all in this together, might as well be friends" Tom, Toonami.

 

mini eLiXiVy: my open source 65% mechanical PCB, a build log, PCB anatomy and discussing open source licenses: https://linustechtips.com/topic/1366493-elixivy-a-65-mechanical-keyboard-build-log-pcb-anatomy-and-how-i-open-sourced-this-project/

 

mini_cardboard: a 4% keyboard build log and how keyboards workhttps://linustechtips.com/topic/1328547-mini_cardboard-a-4-keyboard-build-log-and-how-keyboards-work/

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, minibois said:

With C#, Microsoft's documentation is the best source there is. For example, with String.split they give this is a brief explanation:

https://docs.microsoft.com/en-us/dotnet/api/system.string.split?view=netcore-3.1

It also gives some relevant examples on how to use the function. Very helpful source for anything C# related!

If you already know you just want the names of the days of the week, it's better to just make a list of these names at the start of the program. No need to import a string, split it up, pick up a couple words, etc. really.

But if you don't know the data will always be that, it might be worth it to do it that way.

Yea, that's basically it. 

Get the string > split it > pick out the word(s) you need.

 

But keep in mind, an array starts at 0.

That means words[0] will pick the first word in the array and words[3] will pick out the fourth word in the array for example.

Just something to think about when working with arrays (or really any type of collection, like Lists, Dictionaries, etc.).

I actually have that page open, but I think my brain was flooding with information and array just did not connect with me as it should.

 

My only other issue is, how do I call this value?

 

The value is created within a:

 

public void Main(string[] args)

 

I have a:

 

public void ApplyButton_Click(object sender, RoutedEventArgs e)

 

Where I want to include these particular words in a list of words that are combined to create an output - I have created 50% of the output already, it is just these words that I need to add to the list in the appropriate places.

 

I am calling the other words through the following command:

 

this.OutPutValue.Text += InPutValue.Text;

The first line of which is simply = InPutValue0.Text

 

If I try that line but use mondayString I get the message "does not exist in the current context".

 

Just fyi, the days of the week was just to assist in an explanation, but it won't be days of the week, it will be data that changes with each new spreadsheet. 
 

Thank you for the reminder on 0, I had actually forgotten that while implementing this...

Link to comment
Share on other sites

Link to post
Share on other sites

30 minutes ago, Dravinian said:

My only other issue is, how do I call this value?

The value is created within a: public void Main(string[] args)

I have a: public void ApplyButton_Click(object sender, RoutedEventArgs e)

 

Where I want to include these particular words in a list of words that are combined to create an output - I have created 50% of the output already, it is just these words that I need to add to the list in the appropriate places.

I am calling the other words through the following command:


this.OutPutValue.Text += InPutValue.Text;

The first line of which is simply = InPutValue0.Text

If I try that line but use mondayString I get the message "does not exist in the current context".

There are a million different ways you could go about this. The way I would do is by making a new class, make that class available throughout the main class (the file you're working in now) and call functions/variables from this new class. That way you know all the spreadsheet/word handling stuff is going in a specific place.

 

Create a class (on the right side, in the explorer > Add > Class), make a property in that class (type in 'prop' then press 'Tab' twice) and call this property WordList (or whatever name makes sense in your context) and make that property of the type 'string[]'.

Now create a reference to that class, in your Main class (

 

// The class you already have
using System;

namespace HelloWorld
{
    class Program
    {
    // Reference to the new class
    	WordHandleClass WordClass;
      	
        static void Main(string[] args)
        {          
        // Creating an instance of the WordClass, to be used in this script.
         	WordClass = new WordHandleClass();
            string myString = "the long string you have";
            // You can do this however you want. This will just assume you're sending the large string to the new class and let it deal with it.
            // You could just say 'WordClass.WordString = 'code for splitting string here', but letting the class deal with the objects is generally prefered.
            WordClass.RunCommand(myString);
        }
        
        public void ApplyButton_Click(object sender, RoutedEventArgs e)
        {
        // Call the value from the WordClass.
        	this.OutPutValue.Text += WordClass.WordString[3];        
        }
    }
}

So with this script (which is the class you're working in now), you create a variable at the top (called 'WorldClass', of the 'type' WorldHandleClass'). You then call a function of this WordClass in main (this may or may not be what you want to do, it kinda depends on what you exactly need to do) and then you make that new class and make it hold some property and some functions (perhaps).

// The new class
using System;

namespace HelloWorld
{
    class WordHandleClass
    {
    	// Public property of this class, this will be called from the other class (main)
    	public string[] WordString { get; set; }
        
        // Split the long string into an array and place it in WordString
        public RunCommand(string inputString)
        {
        	// Split the string you give (as a parameter) into the different words.
            // Now place all these words into WordString, which can be called in the Main class using WordClass.WordString[x].
        	WordString = inputString.Split(" ");
        }
    }
}

 

Again, this is one of a million ways this could be done, but it's at least somewhat neat, as you know if you want to change something about the behaviour of splitting the words, you need to be in the WordHandleClass.

You also know in Main, you can call the instance of WordHandleClass ('WordClass') if you want to do something with the words you placed in WordClass.WordStrings.

 

Hope this makes sense, but if anything was unclear; I would be happy to help further.

"We're all in this together, might as well be friends" Tom, Toonami.

 

mini eLiXiVy: my open source 65% mechanical PCB, a build log, PCB anatomy and discussing open source licenses: https://linustechtips.com/topic/1366493-elixivy-a-65-mechanical-keyboard-build-log-pcb-anatomy-and-how-i-open-sourced-this-project/

 

mini_cardboard: a 4% keyboard build log and how keyboards workhttps://linustechtips.com/topic/1328547-mini_cardboard-a-4-keyboard-build-log-and-how-keyboards-work/

Link to comment
Share on other sites

Link to post
Share on other sites

7 minutes ago, minibois said:

There are a million different ways you could go about this. The way I would do is by making a new class, make that class available throughout the main class (the file you're working in now) and call functions/variables from this new class. That way you know all the spreadsheet/word handling stuff is going in a specific place.

 

Create a class (on the right side, in the explorer > Add > Class), make a property in that class (type in 'prop' then press 'Tab' twice) and call this property WordList (or whatever name makes sense in your context) and make that property of the type 'string[]'.

Now create a reference to that class, in your Main class (

 


// The class you already have
using System;

namespace HelloWorld
{
    class Program
    {
    	WordHandleClass WordClass;
      	
        static void Main(string[] args)
        {            
         	WordClass = new WordHandleClass();
            string myString = "the long string you have"
            WordClass.RunCommand(myString);
        }
        
        public void ApplyButton_Click(object sender, RoutedEventArgs e)
        {
        	this.OutPutValue.Text += WordClass.WordString[3];        
        }
    }
}

So with this script (which is the class you're working in now), you create a variable at the top (called 'WorldClass', of the 'type' WorldHandleClass'). You then call a function of this WordClass in main (this may or may not be what you want to do, it kinda depends on what you exactly need to do) and then you make that new class and make it hold some property and some functions (perhaps).


// The class you already have
using System;

namespace HelloWorld
{
    class WordHandleClass
    {
    	public string[] WordString { get; set; }
        
        // Split the long string into an array and place it in WordString
        public RunCommand(string inputString)
        {
        	// Split the string you give (as a parameter) into the different words.
            // Now place all these words into WordString, which can be called in the Main class using WordClass.WordString[x].
        	WordString = inputString.Split(" ");
        }
    }
}

 

Again, this is one of a million ways this could be done, but it's at least somewhat neat, as you know if you want to change something about the behaviour of splitting the words, you need to be in the WordHandleClass.

You also know in Main, you can call the instance of WordHandleClass ('WordClass') if you want to do something with the words you placed in WordClass.WordStrings.

 

Hope this makes sense, but if anything was unclear; I would be happy to help further.

Thanks, I had created a Class but had created a public partial class, and while this stopped the errors popping up, I wasn't actually getting any output.

 

I will read through your post and implement, can't thank you enough man, this stuff was a bit above my paygrade so appreciate you taking the time to explain everything.

Link to comment
Share on other sites

Link to post
Share on other sites

4 minutes ago, Dravinian said:

Thanks, I had created a Class but had created a public partial class, and while this stopped the errors popping up, I wasn't actually getting any output.

I will read through your post and implement, can't thank you enough man, this stuff was a bit above my paygrade so appreciate you taking the time to explain everything.

By the way, I have edited the code/comments a bit (noticed an error in the comments and generally added more info). Please refresh the page for some ore info.

The most important things will be: making the class known in Main (the 'WordHandleClass WordClass;' line in Main), initializing it in Main and having a property in WordHandleClass.

 

Always happy to help with programming stuff! ^^

"We're all in this together, might as well be friends" Tom, Toonami.

 

mini eLiXiVy: my open source 65% mechanical PCB, a build log, PCB anatomy and discussing open source licenses: https://linustechtips.com/topic/1366493-elixivy-a-65-mechanical-keyboard-build-log-pcb-anatomy-and-how-i-open-sourced-this-project/

 

mini_cardboard: a 4% keyboard build log and how keyboards workhttps://linustechtips.com/topic/1328547-mini_cardboard-a-4-keyboard-build-log-and-how-keyboards-work/

Link to comment
Share on other sites

Link to post
Share on other sites

5 minutes ago, minibois said:

Always happy to help with programming stuff! ^^

Well I am glad it isn't too much of an imposition, because this is going a little over my head.

 

Is there not an easier way to call the value of the array we just created?


So far, I have understood .Split, how to use it, how to call from the Array to an immediate WriteLine.  I can write code that pulled from the array and System.Console.Writeline(mondayString) - I know that works if I put it directly under the:

 

string mondayString = words[2]

 

That will write to the console. (I tested it)

 

The only difficult is how do I get it to go across to become available in the ApplyButton_Click section of my code.

 

While I appreciate your coding talent above, it is so far and away above where I am, that I can't explain it, without just repeating what you have said, and nor can I manipulate it to work for me in any other way.

 

Remember, I am quite the newb, and this is a project to assist me to understand certain things, which I always find easiest by trying to do something, learning something, manipulating something and then understanding it.

 

Unfortunately, creating a Class is just too far advanced for me.


I did crate a public partial class MainWindow : Window

 

And create a "private string" with my mondayString name.

 

However, it says it is never assigned, so has a null value.


THis is despite me having:

 

string[] words = phrase.Split(" ");

 

string mondayString = words[2];

 

I know you are right that I likely have to create someway to bring these two things together, but currently, it is a little beyond me and I was hoping for a slightly easier solution so that I could understand it and use it in future.

 

Feel free to tell me there isn't an easier way, and I will come back to this project when I have done a lot more learning.

Link to comment
Share on other sites

Link to post
Share on other sites

@minibois Oh ffs, all I had to do was move the code underneath the ApplyButton_Click header and it recognised it as an array and parsed it into my output (which I had already written).

 

I didnt' realise I could put such an argument under such a header, as I assumed I need the whole public void Main(string[] args) header to create such an argument, but apparently not!

Link to comment
Share on other sites

Link to post
Share on other sites

44 minutes ago, Dravinian said:

I didnt' realise I could put such an argument under such a header, as I assumed I need the whole public void Main(string[] args) header to create such an argument, but apparently not!

This is a confusing thread.

How do you have a Button.Click event handler if you also have a void Main()?

public void Main(string[] args) is the signature for the entry point into a Console application. The Button.Click event is only really useful inside a GUI application.

Something is not making sense to me.

ENCRYPTION IS NOT A CRIME

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, straight_stewie said:

This is a confusing thread.

How do you have a Button.Click event handler if you also have a void Main()?

public void Main(string[] args) is the signature for the entry point into a Console application. The Button.Click event is only really useful inside a GUI application.

Something is not making sense to me.

Probably my poor learning process, of attempting to take something from one place and use it in another to try to get something to work the way I want.

 

I am working my way through a bunch of different tutorials and may have just confused two different parts.


It is one of the many problems with teaching yourself something, until you talk to other people you don't know your own mistakes.

 

I used to teach guitar and it was easier to teach someone who had never played than it was to unteach someone their mistakes.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×