newbie: strings

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

how can I check (as fast as possible) if a string consists only of one
specific character (e.g. ".")?

Thanks
Peter
 
For checking the string length, use String.Length instance member property.
string s = ".";
Console.WriteLine(s.Length);

If you want to check that it is 1 character long and also check this
character to be a specific one:
if (s.Length == 1 && s [0] == '.')
{
Console.WriteLine("The string contains only a '.'");
}
else
{
Console.WriteLine("The string did not match the test.");
}

As you see, indexing can be used with System.String to refer to specific
characters within it.
 
Another way, that I use is: "MessageBox.Show(MyInput);" If you are using
windows forms

MikeY
 
:-) I didn't make myself clear enough...how can i check if a string of random
length consists only of one character? e.g. "...." or "........." or ".", but
not ".dde..."...

Peter
 
You could do

string s = "Hello World";
if(s.IndexOf(".") != -1 && s.IndexOf(".") == s.LastIndexOf("."))
// s contains exactly 1 .
 
This is one wayi could think of:
public static bool ConsistsOfRepeatingCharacter ( string s )
{
if (s == null)
throw new ArgumentNullException("s");
if (s.Length == 0)
throw new ArgumentNullException("Must be at least 1 character
long.", "s");
char c = s [0];
for (int i = 1; i < s.Length; i ++)
{
if (c != s )
{
return false;
}
}
return true;
}
 
How about this:

private bool StringChecker(string inString)
{
return(inString.Length>0 &&
inString.Replace(inString.Substring(0,1),"").Length ==0)
}
 
Peter,

I saw you where using VBNet

\\\
Dim a As String = "...a"
For Each b As Char In a
If b <> "."c Then
MessageBox.Show("I am a character " & b)
End If
Next
///
I hope this helps,

Cor
 
Peter said:
:-) I didn't make myself clear enough...how can i check if a string of random
length consists only of one character? e.g. "...." or "........." or ".", but
not ".dde..."...

Regex.IsMatch(Text, @"[^\.]")
 
Back
Top