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 said:
Sling said:
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 = stringWithSentence.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
, which is I think equally
simple as what you describe.
-Lenard