C# check to see if an input contains only lowercase letters a-z - string

I'm stuck on a task of trying to print words that contain only lowercase letters a-z. I have already stripped out an inputted string if it contains any number 0-9 and if it contains an Uppercase letter:
String[] textParts;
textParts = text.Split(delimChars);
for (int i = 0; i < textParts.Length; i++) //adds s to words list and checks for capitals
{
String s = textParts[i];
bool valid = true;
foreach (char c in textParts[i])
{
if (char.IsUpper(c))
{
valid = false;
break;
}
if (c >= '0' && c <= '9')
{
valid = false;
break;
}
if (char.IsPunctuation(c))
{
valid = false;
break;
}
}
if (valid) pageIn.words.Add(s);
This is my code so far. The last part I'm trying to check to see if a word contains any punctuation (it's not working) is there an easier way I could do this and how could I get the last part of my code to work?
P.S. I'm not that comfortable with using Regex.
Many Thanks,
Ellie

Without regex, you can use LINQ (might be less performant)
bool isOnlyLower = s.Count(c => Char.IsLower(c)) == s.Length;
Count will retrieve the number of char that are in lower in the following string. If it match the string's length, string is composed only of lowercase letters.
An alternative would be to check if there's any UpperCase :
bool isOnlyLower = !s.Any(c => Char.IsUpper(c));

var regex = new Regex("^[a-z]+$");
if (!regex.IsMatch(input))
{
// is't not only lower case letters, remove input
}

I'm not sure whether I get your question right, but shouldn't the following work?
for (int i = 0; i < textParts.Length; i++) //adds s to words list and checks for capitals
{
String s = textParts[i];
if(s.Equals(s.ToLower()))
{
// string is all lower
}
}

Related

Program to find if a string is a palindrome keeps on failing. Even after using toLowerCase() command for both strings, output doesn't come

import java.util.Scanner;
class Palindrome_string
{
public static void main()
{
System.out.println("\f");
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string");
String a = sc.nextLine();
int b = a.length();
String rev = "";
for (int i = b - 1; i >= 0; i--)
{
char c = a.charAt(i);
rev = rev + c;
}
System.out.println("Original word "+a);
System.out.println("Reversed word "+rev);
a = a.toLowerCase();
rev = rev.toLowerCase();
if (a == rev)
{
System.out.println("It is a palindrome");
}
else
{
System.out.println("It is not a palindrome");
}
sc.close();
}
}
The program compiles properly. Still, when running the program, the message which tells if it is a palindrome prints incorrectly. What changes do I make? Here is a picture of the output. Even though the word 'level' (which is a palindrome) has been inputted, it shows that it isn't a palindrome. What changes should I make? output pic
You should not use == to compare two strings because it compares the reference of the string, i.e. whether they are the same object or not.
Use .equals() instead. It tests for value equality. So in your case:
if (a.equals(rev))
{
System.out.println("It is a palindrome");
}
Also try not to use single-letter variable names except for index variables when iterating over a list etc. It's bad practice.

Replacing the number in a string

if my string is lets say "Alfa1234Beta"
how can I convert all the number in to "_"
for example "Alfa1234Beta"
will be "Alfa____Beta"
Going with the Regex approach pointed out by others is possibly OK for your scenario. Mind you however, that Regex sometimes tend to be overused. A hand rolled approach could be like this:
static string ReplaceDigits(string str)
{
StringBuilder sb = null;
for (int i = 0; i < str.Length; i++)
{
if (Char.IsDigit(str[i]))
{
if (sb == null)
{
// Seen a digit, allocate StringBuilder, copy non-digits we might have skipped over so far.
sb = new StringBuilder();
if (i > 0)
{
sb.Append(str, 0, i);
}
}
// Replace current character (a digit)
sb.Append('_');
}
else
{
if (sb != null)
{
// Seen some digits (being replaced) already. Collect non-digits as well.
sb.Append(str[i]);
}
}
}
if (sb != null)
{
return sb.ToString();
}
return str;
}
It is more light weight than Regex and only allocates when there is actually something to do (replace). So, go ahead use the Regex version if you like. If you figure out during profiling that is too heavy weight, you can use something like the above. YMMV
You can run for loop on the string and then use the following method to replace numbers with _
if (!System.Text.RegularExpressions.Regex.IsMatch(i, "^[0-9]*$"))
Here variable i is the character in the for loop .
You can use this:
var s = "Alfa1234Beta";
var s2 = System.Text.RegularExpressions.Regex.Replace(s, "[0-9]", "_");
s2 now contains "Alfa____Beta".
Explanation: the regex [0-9] matches any digit from 0 to 9 (inclusive). The Regex.Replace then replaces all matched characters with an "_".
EDIT
And if you want it a bit shorter AND also match non-latin digits, use \d as a regex:
var s = "Alfa1234Beta๓"; // ๓ is "Thai digit three"
var s2 = System.Text.RegularExpressions.Regex.Replace(s, #"\d", "_");
s2 now contains "Alfa____Beta_".

How do I convert a string to lowercase?

I don't know how to convert a word into complete lowercase in cs50. I have to convert words into lowercase to check it properly.
Below is my code so far
bool check(const char *word) {
char *lword[strlen(word)];
for (i = 0; i < strlen(word); i++) {
lword[i] = tolower(int
word[i]);
}
node *current;
int hashnum = hash(word);
if (table[hashnum] == NULL)
return false;
current = table[hashnum];
while (current->next != NULL) {
if (strcmp(current->word, word) == 0)
return true;
else
current = current->next;
}
return false;
}
This declaration char *lword[strlen(word)]; is a problem. it declares lword as an array of strings (aka char*). An array of chars would be more appropriate. (Also, program would probably complain when lword is sent as an argument to hash function.) Don't forget to declare the lower case word large enough to accommodate the null-terminator, and null-terminate it. Don't forget to send the lower-case word to hash, instead of the original word.

Alphabet string code, looping

So I need to finish this program that asks user to type in a word and then he needs to write it back "encrypted", only in number. So a is 1, b is 2... For example if I give the word "bad", it should come back as "2 1 4". The program I made seems to do this always only for the 1st letter of the word. My question that I would need help with is, why does this program stop looping after the 1st letter? Am I even doin it right or is it completely off? Any help would be much appreciated.
Console.Write("Please, type in a word: ");
string start = Console.ReadLine();
string alphabet = "abcdefghijklmnopqrstuvwxyz";
for (int c = 0; c < alphabet.Length; c++)
{
int a = 0;
if (start[a] == alphabet[c])
{
Console.Write(c + 1);
a++;
continue;
}
if (start[a] != alphabet[c])
{
a++;
continue;
}
}
I accomplished it with a nested loop:
Console.Write("Please, type in a word: ");
string start = Console.ReadLine();
string alphabet = "abcdefghijklmnopqrstuvwxyz";
for (int a = 0; a < start.Length; a++)
{
for (int c = 0; c < alphabet.Length; c++)
{
if (start[a] == alphabet[c])
{
Console.Write(c + 1);
}
}
}
While comparing the strings, it makes sense, at least to me, to loop through both of them.
Your program was stopping after the first letter because your were resetting "a" to 0 at the beginning of every loop.

Need a program to reverse the words in a string

I asked this question in a few interviews. I want to know from the Stackoverflow readers as to what should be the answer to this question.
Such a seemingly simple question, but has been interpreted quite a few different ways.
if your definition of a "word" is a series of non-whitespace characters surrounded by a whitespace character, then in 5 second pseudocode you do:
var words = split(inputString, " ")
var reverse = new array
var count = words.count -1
var i = 0
while count != 0
reverse[i] = words[count]
count--
i++
return reverse
If you want to take into consideration also spaces, you can do it like that:
string word = "hello my name is";
string result="";
int k=word.size();
for (int j=word.size()-1; j>=0; j--)
{
while(word[j]!= ' ' && j>=0)
j--;
int end=k;
k=j+1;
int count=0;
if (j>=0)
{
int temp=j;
while (word[temp]==' '){
count++;
temp--;
}
j-=count;
}
else j=j+1;
result+=word.substr(k,end-k);
k-=count;
while(count!=0)
{
result+=' ';
count--;
}
}
It will print out for you "is name my hello"
Taken from something called "Hacking a Google Interview" that was somewhere on my computer ... don't know from where I got it but I remember I saw this exact question inside ... here is the answer:
Reverse the string by swapping the
first character with the last
character, the second with the
second-to-last character, and so on.
Then, go through the string looking
for spaces, so that you find where
each of the words is. Reverse each of
the words you encounter by again
swapping the first character with the
last character, the second character
with the second-to-last character, and
so on.
This came up in LessThanDot Programmer Puzzles
#include<stdio.h>
void reverse_word(char *,int,int);
int main()
{
char s[80],temp;
int l,i,k;
int lower,upper;
printf("Enter the ssentence\n");
gets(s);
l=strlen(s);
printf("%d\n",l);
k=l;
for(i=0;i<l;i++)
{
if(k<=i)
{temp=s[i];
s[i]=s[l-1-i];
s[l-1-i]=temp;}
k--;
}
printf("%s\n",s);
lower=0;
upper=0;
for(i=0;;i++)
{
if(s[i]==' '||s[i]=='\0')
{upper=i-1;
reverse_word(s,lower,upper);
lower=i+1;
}
if(s[i]=='\0')
break;
}
printf("%s",s);
return 0;
}
void reverse_word(char *s,int lower,int upper)
{
char temp;
//int i;
while(upper>lower)
{
temp=s[lower];
s[lower]=s[upper];
s[upper]=temp;
upper=upper-1;
lower=lower+1;
}
}
The following code (C++) will convert a string this is a test to test a is this:
string reverseWords(string str)
{
string result = "";
vector<string> strs;
stringstream S(str);
string s;
while (S>>s)
strs.push_back(s);
reverse(strs.begin(), strs.end());
if (strs.size() > 0)
result = strs[0];
for(int i=1; i<strs.size(); i++)
result += " " + strs[i];
return result;
}
PS: it's actually a google code jam question, more info can be found here.

Resources