473,715 Members | 2,192 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to extract words out from a string?

I code in Rexx on the mainframe which has 2 built-in functions: word(s,i) &
words(s).
word(s,i) returns the ith word in the s(tring), and words(s) returns the
number of words within the s(tring).

Is there something equivalent in C#, preferably built-in (assumed better
performance), or sample code?

Thanks in advance.
Dec 13 '05 #1
7 43613
Sling wrote:
I code in Rexx on the mainframe which has 2 built-in functions: word(s,i) &
words(s).
word(s,i) returns the ith word in the s(tring), and words(s) returns the
number of words within the s(tring).

Is there something equivalent in C#, preferably built-in (assumed better
performance), or sample code?

Thanks in advance.


Assuming your words are space separated, you could try:

string[] words = stringWithSente nce.Split ( new char[] { ' ' } );

After this, words will be an array of words. The words come from the
string, and the space character is used as separation (the string is
split on the space character). You could specify one or more separator
character for the Split method.

You can get the number of words you got by using words.Length property,
and can get the ith word by using words[i], which is I think equally
simple as what you describe.

-Lenard
Dec 13 '05 #2
Thanks, Lenard. What if my string s contains: "This is a test string
with more than 1 space in between "? Words(s) from Rexx returns 12, and
word(s,5) returns "string". Would I be able to get something similar back
from C#?

"Lenard Gunda" wrote:
Sling wrote:
I code in Rexx on the mainframe which has 2 built-in functions: word(s,i) &
words(s).
word(s,i) returns the ith word in the s(tring), and words(s) returns the
number of words within the s(tring).

Is there something equivalent in C#, preferably built-in (assumed better
performance), or sample code?

Thanks in advance.


Assuming your words are space separated, you could try:

string[] words = stringWithSente nce.Split ( new char[] { ' ' } );

After this, words will be an array of words. The words come from the
string, and the space character is used as separation (the string is
split on the space character). You could specify one or more separator
character for the Split method.

You can get the number of words you got by using words.Length property,
and can get the ith word by using words[i], which is I think equally
simple as what you describe.

-Lenard

Dec 13 '05 #3
I tried but failed to find something similar in .NET framework, so I ended up
writing the subroutines myself, as follow:
static string Word(string s, int i) {
string w = "";
int c = 0;
s = s.Trim();
if (s.Length > 0 && i > 0) {
for (int x = 0; x <= s.Length-1; x++) {
if (s.Substring(x, 1) == " ") {
while (x <= s.Length-1 && s.Substring(x,1 ) == " ")
x++;
}
else {
c = c + 1;
if (c == i) {
while (x <= s.Length-1 && s.Substring(x,1 ) != " ") {
w = w + s.Substring(x,1 );
x++;
}
return w;
}
else {
while (x <= s.Length-1 && s.Substring(x,1 ) != " ")
x++;
}
}
x--;
}
}
return w;
} // end of function Word..

static int Words(string strIn) {
int w = 0;
string str1 = strIn.Trim();
if (str1.Length > 0) {
for (int x = 0; x <= str1.Length-1; x++) {
if (str1.Substring (x,1) == " ")
while (x <= str1.Length-1 && str1.Substring( x,1) == " ")
x++;
else {
w++;
while (x <= str1.Length-1 && str1.Substring( x,1) != " ")
x++;
}
x--;
}
}
return w;
} // end of function Words..

Anyone got anything better (performance wise)?

Thanks, Lenard. What if my string s contains: "This is a test string
with more than 1 space in between "? Words(s) from Rexx returns 12, and
word(s,5) returns "string". Would I be able to get something similar back
from C#?

"Lenard Gunda" wrote:
Sling wrote:
I code in Rexx on the mainframe which has 2 built-in functions: word(s,i) &
words(s).
word(s,i) returns the ith word in the s(tring), and words(s) returns the
number of words within the s(tring).

Is there something equivalent in C#, preferably built-in (assumed better
performance), or sample code?

Thanks in advance.


Assuming your words are space separated, you could try:

string[] words = stringWithSente nce.Split ( new char[] { ' ' } );

After this, words will be an array of words. The words come from the
string, and the space character is used as separation (the string is
split on the space character). You could specify one or more separator
character for the Split method.

You can get the number of words you got by using words.Length property,
and can get the ith word by using words[i], which is I think equally
simple as what you describe.

-Lenard

Dec 13 '05 #4
Hi,

For your test string the code I provided would return more than 12,
because it would find the empty strings as well. The array would then
contain multiple empty elements. This is the situation with .NET 1.1

In .NET 2.0 you could add an options parameter to the Split method call:

string[] words = stringWithSente nce.Split ( new char[] { ' ' },
StringSplitOpti ons.RemoveEmpty Entries );

This would remove the empty elements from the returned array. This is
what you need I think. But this behaviour is only available in .NET 2.0.

-Lenard
Sling wrote:
Thanks, Lenard. What if my string s contains: "This is a test string
with more than 1 space in between "? Words(s) from Rexx returns 12, and
word(s,5) returns "string". Would I be able to get something similar back
from C#?

"Lenard Gunda" wrote:

Sling wrote:
I code in Rexx on the mainframe which has 2 built-in functions: word(s,i) &
words(s).
word(s,i) returns the ith word in the s(tring), and words(s) returns the
number of words within the s(tring).

Is there something equivalent in C#, preferably built-in (assumed better
performance) , or sample code?

Thanks in advance.


Assuming your words are space separated, you could try:

string[] words = stringWithSente nce.Split ( new char[] { ' ' } );

After this, words will be an array of words. The words come from the
string, and the space character is used as separation (the string is
split on the space character). You could specify one or more separator
character for the Split method.

You can get the number of words you got by using words.Length property,
and can get the ith word by using words[i], which is I think equally
simple as what you describe.

-Lenard

Dec 13 '05 #5
Sling <cs***********@ hotmail.com> wrote:
I tried but failed to find something similar in .NET framework, so I ended up
writing the subroutines myself, as follow:


<snip>

Aside from anything else, you should know about a couple of performance
things:

1) Taking a single character substring creates a new object needlessly.
Just use the indexer to return a character.

2) Use a StringBuilder to build strings, rather than repeated string
concatenation.

Now, I'd say the best way of doing the main split is to use a regular
expression. For instance:

using System;
using System.Text.Reg ularExpressions ;

class Test
{
static void Main()
{
string x = "This is a test string"+
" with more than 1 space in between ";

foreach (string word in Regex.Split (x, @"\s+"))
{
Console.WriteLi ne ("'{0}'", word);
}
}
}

The results are:
'This'
'is'
'a'
'test'
'string'
'with'
'more'
'than'
'1'
'space'
'in'
'between'
''

Note the final empty string, because there's a space at the end. If you
don't want that, trim the string first (call String.Trim and use the
result as the input to Regex.Split).

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 13 '05 #6
tjb
"Sling" <cs***********@ hotmail.com> posted:
I tried but failed to find something similar in .NET framework, so I ended up
writing the subroutines myself, as follow:


<snip>

As Jon said, use a regex. If you want to learn all about
regexes---and I would recommend doing so, as they can be *very*
handy---an online tutorial can be found at
<http://www.regular-expressions.inf o/>.
Dec 13 '05 #7
Thanks, Jon & tjb. Will give this a try.

"Jon Skeet [C# MVP]" wrote:
Sling <cs***********@ hotmail.com> wrote:
I tried but failed to find something similar in .NET framework, so I ended up
writing the subroutines myself, as follow:


<snip>

Aside from anything else, you should know about a couple of performance
things:

1) Taking a single character substring creates a new object needlessly.
Just use the indexer to return a character.

2) Use a StringBuilder to build strings, rather than repeated string
concatenation.

Now, I'd say the best way of doing the main split is to use a regular
expression. For instance:

using System;
using System.Text.Reg ularExpressions ;

class Test
{
static void Main()
{
string x = "This is a test string"+
" with more than 1 space in between ";

foreach (string word in Regex.Split (x, @"\s+"))
{
Console.WriteLi ne ("'{0}'", word);
}
}
}

The results are:
'This'
'is'
'a'
'test'
'string'
'with'
'more'
'than'
'1'
'space'
'in'
'between'
''

Note the final empty string, because there's a space at the end. If you
don't want that, trim the string first (call String.Trim and use the
result as the input to Regex.Split).

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Dec 13 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
4402
by: Lydia Shawn | last post by:
hi there, i want to extract the numbers from this example input: bla trigger3 trigger4 trigger1 blabla trigger1 5000.00 trigger3 trigger1 trigger2 trigger2 600.00 trigger4 trigger1 50.00 trigger4
9
16977
by: Sharon | last post by:
hi, I want to extract a string from a file, if the file is like this: 1 This is the string 2 3 4 how could I extract the string, starting from the 10th position (i.e. "T") and extract 35 characters (including "T") from a file and then go to next line?
3
2754
by: Maya | last post by:
Hello guys, Is there an easy way to extract individual words that form a string and store them in variables like in this example: String "how are you?" My result would be: var1 = "how"
0
1300
by: kamal9 | last post by:
#include <stdio.h> #include <string.h> void string2Lines(char line, char tokens){ char *token_ptr, token; char *i=";" " " "," "." "?" "!"; token_ptr = strtok(line, i ); while(token_ptr){ strcpy(token, token_ptr); strcat(tokens, strcat(token,"\n"));
17
2893
by: Umesh | last post by:
Can anyone do it? ARMY1987- what say?
0
1435
by: wbw | last post by:
I am trying to extract capitalized words from text in Excel. I have a list of a combination of brands and products and I am trying to extract out the product attribute from the text. Since the text varies in length, I cannot use standard text parsing excel functions to extract the product from the text. I could use text to columns but that gets labor intensive. Is there a way to extract out the capitalized words from text in Excel? How do I...
1
2724
by: Edwin.Madari | last post by:
from each line separate out url and request parts. split the request into key-value pairs, use urllib to unquote key-value pairs......as show below... import urllib line = "GET...
0
1373
by: JohanA | last post by:
I´m using Apose.words to extract diagrams from word 2003 documents. It´s no problem to iterate the embedded MSGraph.Chart.8 objects but I can´t read the data from them. Anyone who knows how to do it? Thank´s in advance! Johan
3
3523
by: Nen013 | last post by:
So I'm trying to create a function that will extract a word from a string. I'm trying to do this without creating an array. So far I have this: string s = "Hello World"; string t; for (size_t k = 0; k!=s.size(); k++) {if (isalpha(s)) t+=s; else ???; }
0
8817
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8715
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9322
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9092
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9037
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7963
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5964
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4734
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2531
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.