For loop construction and code complexity [closed] - for-loop

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
My group is having some discussion and strong feelings about for loop construction.
I have favored loops like:
size_t x;
for (x = 0; x < LIMIT; ++x) {
if (something) {
break;
}
...
}
// If we found what we're looking for, process it.
if (x < LIMIT) {
...
}
But others seem to prefer a Boolean flag like:
size_t x;
bool found = false;
for (x = 0; x < LIMIT && !found; ++x) {
if (something) {
found = true;
}
else {
...
}
}
// If we found what we're looking for, process it.
if (found) {
...
}
(And, where the language allows, using "for (int x = 0; ...".)
The first style has one less variable to keep track of and a simpler loop header. Albeit at the cost of "overloading" the loop control variable and (some would complain), the use of break.
The second style has clearly defined roles for the variables but a more complex loop condition and loop body (either an else, or a continue after found is set, or a "if (!found)" in the balance of the loop).
I think that the first style wins on code complexity. I'm looking for opinions from a broader audience. Pointers to actual research on which is easier to read and maintain would be even better. "It doesn't matter, take it out of your standard" is a fine answer, too.
OTOH, this may be the wrong question. I'm beginning to think that the right rule is "if you have to break out of a for, it's really a while."
bool found = false;
x = 0;
while (!found && x < LIMIT) {
if (something) {
found = true;
...handle the thing...
}
else {
...
}
++x;
}
Does what the first two examples do but in fewer lines. It does divide the initialization, test, and increment of x across three lines, though.

I'd actually dare to suggest consideration of GOTO to break out of loops in such cases:
for (size_t x = 0; x < LIMIT && !found; ++x) {
if (something)
goto found;
else {
...
}
}
// not found
...
return;
found:
...
return;
I consider this form to be both succint and readable. It may do some good in many simple cases (say, when there is no common processing in this function, in both found/unfound cases).
And about the general frowning goto receives, I find it to be a common misinterpretation of Dijkstra's original claims: his arguments favoured structured loop clauses, as for or while, over a primitive loop-via-goto, that still had a lot of presence circa 1968. Even the almighty Knuth eventualy says -
The new morality that I propose may
perhaps be stated thus: "Certain go to
statements which arise in connection with
well-understood transformations are acceptable, provided that the program documentation explains what the transformation was."
Others here occasionaly think the same.

While I disagree that an extra else really makes the 2nd more complicated, I think it's primarily a matter of aesthetics and keeping to your standard.
Personally, I have a probably irrational dislike of breaks and continues, so I'm MUCH more likely to use the found variable.
Also, note that you CAN add the found variable to the 1st implementation and do
if(something)
{
found = true;
break;
}
if you want to avoid the variable overloading problem at the expense of the extra variable, but still want the simple loop terminator...

The former example duplicates the x < LIMIT condition, whereas the latter doesn't.
With the former, if you want to change that condition, you have to remember to do it in two places.

I would prefer a different one altogether:
for (int x = 0; x < LIMIT; ++x) {
if (something) {
// If we found what we're looking for, process it.
...
break;
}
...
}
It seems you have not any trouble you mention about one or the other... ;-)
no duplication of condition, or readability problem
no additional variable

I don't have any references to hand (-1! -1!), but I seem to recall that having multiple exit points (from a function, from a loop) has been shown to cause issues with maintainability (I used to know someone who wrote code for the UK military and it was Verboten to do so). But more importantly, as RichieHindle points out, having a duplicate condition is a Bad Thing, it cries out for introducing bugs by changing one and not the other.
If you weren't using the condition later, I wouldn't be bothered either way. Since you are, the second is the way to go.

This sort of argument has been fought out here before (probably many times) such as in this question.
There are those that will argue that purity of code is all-important and they'll complain bitterly that your first option doesn't have identical post-conditions for all cases.
What I would answer is "Twaddle!". I'm a pragmatist, not a purist. I'm as against too much spaghetti code as much as the next engineer but some of the hideous terminating conditions I've seen in for loops are far worse than using a couple of breaks within your loop.
I will always go for readability of code over "purity" simply because I have to maintain it.

This looks like a place for a while loop. For loops are Syntactic Sugar on top of a While loop anyway. The general rule is that if you have to break out of a For loop, then use a While loop instead.

package com.company;
import java.io.*;
import java.util.Scanner;
public class Main {
// "line.separator" is a system property that is a platform independent and it is one way
// of getting a newline from your environment.
private static String NEWLINE = System.getProperty("line.separator");
public static void main(String[] args) {
// write your code here
boolean itsdone = false;
String userInputFileName;
String FirstName = null;
String LastName = null;
String user_junk;
String userOutputFileName;
String outString;
int Age = -1;
int rint = 0;
int myMAX = 100;
int MyArr2[] = new int[myMAX];
int itemCount = 0;
double average = 0;
double total = 0;
boolean ageDone = false;
Scanner inScan = new Scanner(System.in);
System.out.println("Enter First Name");
FirstName = inScan.next();
System.out.println("Enter Last Name");
LastName = inScan.next();
ageDone = false;
while (!ageDone) {
System.out.println("Enter Your Age");
if (inScan.hasNextInt()) {
Age = inScan.nextInt();
System.out.println(FirstName + " " + LastName + " " + "is " + Age + " Years old");
ageDone = true;
} else {
System.out.println("Your Age Needs to Have an Integer Value... Enter an Integer Value");
user_junk = inScan.next();
ageDone = false;
}
}
try {
File outputFile = new File("firstOutFile.txt");
if (outputFile.createNewFile()){
System.out.println("firstOutFile.txt was created"); // if file was created
}
else {
System.out.println("firstOutFile.txt existed and is being overwritten."); // if file had already existed
}
// --------------------------------
// If the file creation of access permissions to write into it
// are incorrect the program throws an exception
//
if ((outputFile.isFile()|| outputFile.canWrite())){
BufferedWriter fileOut = new BufferedWriter(new FileWriter(outputFile));
fileOut.write("==================================================================");
fileOut.write(NEWLINE + NEWLINE +" You Information is..." + NEWLINE + NEWLINE);
fileOut.write(NEWLINE + FirstName + " " + LastName + " " + Age + NEWLINE);
fileOut.write("==================================================================");
fileOut.close();
}
else {
throw new IOException();
}
} // end of try
catch (IOException e) { // in case for some reason the output file could not be created
System.err.format("IOException: %s%n", e);
e.printStackTrace();
}
} // end main method
}

Related

Sudoku solver with backtracking can't always detect multiple solutions

This is the code I wrote to check if there are multiple solutions to a KenKen puzzle (Similar to Sudoku). Technically it should return true if there are 2 solutions, but it doesn't appear to work because of a logic error in the algorithm.
I can't seem to find the error and after spending a whole day debugging the whole thing step by step I feel like I'll never find out what's wrong.
The code can solve the puzzle without any problems but it doesn't always seem to detect when there are multiple solutions, which is just weird.
boolean solutionFlag = false;
static boolean backtrackingUniqueSolution(int startIndex) {
for (int i=1; i<=sudokuGridElements.length; i++){
sudokuGridCells[startIndex] = i;
if(checkConditons()){
if(endOfBounds || backtrackingUniqueSolution(startIndex + 1))){
if(!solutionFlag){ //Used to "count to 1"
solutionFlag = true;
} else {
return true; //Should return true only after it finds the second solution
}
}
}
sudokuGridCells[startIndex] = null;
}
return false;
}
When you find the first solution, you set the flag, but return false, so that you don't know whether a solution was found further up the recursion stack. The flag tells you that, but you must still look for a second solution to get your answer.
You should distinguish between actually finding a solution when the last cell is reached and cutting recursion short when you already have found a second solution. In the first case, do the delayed counting via the flag. In the second case, just return true if a second solution was found, that is when the recursive function has returned true.
boolean solutionFlag = false;
static boolean multiSolution(int startIndex) {
for (int i = 1; i <= sudokuGridElements.length; i++) {
sudokuGridCells[startIndex] = i;
if(checkConditons()) {
if (endOfBounds) {
if (solutionFlag) return true;
solutionFlag = true;
} else {
if (multiSolution(startIndex + 1)) return true;
}
}
sudokuGridCells[startIndex] = null;
}
return false;
}
(You could get rid of the non-local state flag, if you made the function return an integer or enumerated value which tells you whether no, a single or many solutions were found.)

Which coding style is more readable or preferable? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
In the below 2 ways, which method one has to prefer. I personally comfortable with method 2, the if-elseladder one. But my friend told, they invoke redundancy in coding., and he used to achieve that in many single if statements, like..
Examples:
if( cond1 && cond2 ){}
if(cond1 && cond3){}
if(cond3 && cond2){} etc..
Instead of.,
if(cond1)
{
}
else
{
if(cond3 && cond2)
{}
}
//Way 1
String str = cond1 && !cond2 && !cond3 ? "world" : "hello" ;
(cond1,cond2,cond3 -> aren't simple checks. say they itself contains many || and &&'s )
//Way 2
String str;
if (cond1)
{
if (cond2)
{
str = "hello";
}
else
{
if (cond3)
{
str = "hello";
}
else
{
str = "world";
}
}
}
String str;
if (cond1 && cond2) {
str = "hello";
} else if(cond1 && cond3) {
str = "hello";
} else if(cond1) {
str = "world";
}
This method is a bit inbetween the two. I am not a fan of the first method at all. But personally, this method seems a bit more clear than your second method and more readable, and it does the same thing.
This isn't to suggest that you should avoid nesting if statements. I'm merely suggesting that you should feel free to use compound if statements also. In my opinion, the contents of an if else block should be more than just more nested if or if else. If there is nothing inside your if block that's not in a nested if block, then your statement can be rewritten with compound if statements.
There's an alternate to my first method also.
String str;
if(cond1) {
if(cond2) {
//do stuff
} else if(cond3) {
//do stuff
} else {
//do stuff
}
}
This will check cond1 just once. It still has a purely nested if that can be rewritten as compound, but if you're concerned about performance (if cond1 is a particularly time-consuming check), this will check cond1 just once, and it still more readable than what you offered in the question originally (in my opinion). This difference is more subtle.
There's also this method.
bool flag1 = cond1;
bool flag2 = cond2;
bool flag3 = cond3;
String str;
if (flag1 && flag2) {
str = "hello";
} else if(flag1 && flag3) {
str = "hello";
} else if(flag1) {
str = "world";
}
In this method, you can make simple and short compound condition statements by using bool variables as flags. You can check any of the conditions as many times as you want (any time the condition may change, you need to flag1 = cond1 again, etc), without doing all the computing it may take to actually check the condition. You just check it once and save the result of the condition.
I have seen many different types of coding styles and from all that I have found, it all depends on the situation. There is not a universal standard, other than do not write un-readable code.
Your colleagues may desire a specific stylistic pattern and thus you follow that one.
To a moderately experienced programmer both are very readable and readability is very important for code, especially if it is going to be maintained by somebody else(which is eventually inevitable).
It is all what your goals are. If you want large if/else statements, I am not sure there is an inherent reason not too, other than it may eventually make unreadable code, depending on how it is implemented.

Trouble With Java Program using parameters and methods [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am stuck here with one programming code: Here are the instructions: http://my.fit.edu/~akhademzadeh2011/courses/cse1001/f2012/ass/ass04.pdf
And, this is my code:
import java.util.*;
public class PantherSolver {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
String input;
String p = "0| |";
int signcontrol = 1;
input = GUI(p);
int firstnumber = inputmethod(input);
int firstsign = sign(input,signcontrol);
String secondp = p1(firstsign,firstnumber,p);
String input2 = GUI(secondp);
}
public static String p1(int firstsign,int firstnumber, String p) {
if (firstsign>0) {
p = "0| "+ firstnumber +" |";
}
else {
p = "0| -"+ firstnumber +" |";
}
return p;
}
public static String GUI1(String secondp) {
Scanner kb = new Scanner(System.in);
String newinput = kb.nextLine();
System.out.println(" 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
System.out.println(" ========================================");
System.out.println(secondp);
System.out.println("1|--------------------------------------|");
System.out.println("2| OFF +/- AC |");
System.out.println("3| 1 2 3 4 5 , |");
System.out.println("4| 6 7 8 9 0 SOLVE |");
System.out.println(" ========================================");
System.out.println(" Key: " + newinput +"");
return newinput;
}
public static String GUI(String p) {
Scanner kb = new Scanner(System.in);
System.out.println(" 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
System.out.println(" ========================================");
System.out.println(p);
System.out.println("1|--------------------------------------|");
System.out.println("2| OFF +/- AC |");
System.out.println("3| 1 2 3 4 5 , |");
System.out.println("4| 6 7 8 9 0 SOLVE |");
System.out.println(" ========================================");
String input1=kb.nextLine();
System.out.println(" Key: " + input1 +"");
return input1;
}
public static int inputmethod(String input) {
Scanner kb = new Scanner(System.in);
int a = 0;
if (input.length()==2) {
if((input.charAt(0)=='0')||(input.charAt(0)=='1')) {
;
}
else if((input.charAt(0)=='2') && !((input.charAt(1)==('0'))||(input.charAt(1)==('1'))||(input.charAt(1)==('2'))||(input.charAt(1)==('S'))||(input.charAt(1)==('T'))||(input.charAt(1)==('U'))||(input.charAt(1)==('V'))||(input.charAt(1)==('W'))||(input.charAt(1)==('X'))||(input.charAt(1)==('Y'))||(input.charAt(1)==('Z')))) {
;
}
else if((input.charAt(0)=='3') && !((input.charAt(1)==('0'))||(input.charAt(1)==('2'))||(input.charAt(1)==('4'))||(input.charAt(1)==('6'))||(input.charAt(1)==('8'))||(input.charAt(1)==('T'))||(input.charAt(1)==('U')))) {
;
}
else if((input.charAt(0)=='4') && !((input.charAt(1)==('0'))||(input.charAt(1)==('2'))||(input.charAt(1)==('4'))||(input.charAt(1)==('6'))||(input.charAt(1)==('8'))||(input.charAt(1)==('U'))||(input.charAt(1)==('V'))||(input.charAt(1)==('W'))||(input.charAt(1)==('X'))||(input.charAt(1)==('Y'))||(input.charAt(1)==('Z')))) {
;
}
else if ((input.equals("20")) || (input.equals("21")) ||(input.equals("22")) ||(input.equals("2S")) ||(input.equals("2T")) ||(input.equals("2U")) ||(input.equals("2V")) ||(input.equals("2X")) ||(input.equals("2Y")) ||(input.equals("2Z")) ||(input.equals("30")) ||(input.equals("32")) ||(input.equals("34")) ||(input.equals("36")) ||(input.equals("38")) ||(input.equals("40")) ||(input.equals("42")) ||(input.equals("44")) ||(input.equals("46")) ||(input.equals("48")) ||(input.equals("4U")) ||(input.equals("4V")) ||(input.equals("4W")) ||(input.equals("4X")) ||(input.equals("4Y")) ||(input.equals("4Z"))) {
switch(input) {
case "20":
case "21":
case "22":
OFF();
break;
case "2X":
case "2Y":
case "2Z":
main(null);
break;
case "30":
a = 1;
break;
case "32":
a = 2;
break;
case "34":
a = 3;
break;
case "36":
a = 4;
break;
case "38":
a = 5;
break;
case "40":
a = 6;
break;
case "42":
a = 7;
break;
case "44":
a = 8;
break;
case "46":
a = 9;
break;
case "48":
a = 0;
break;
case "4U":
case "4V":
case "4W":
case "4X":
case "4Y":
case "4Z":
solve();
break;
}
}
else {
System.out.println("Invalid key.");
System.out.println(" Key: " + input+"");
inputmethod(input);
}
}
else {
System.out.println("Invalid key.");
System.out.println(" Key: " + input +"");
inputmethod(input);
}
return a;
}
public static int sign (String input, int signcontrol) {
int sign1 = signcontrol;
if ((input.equals("2S")) ||(input.equals("2T")) ||(input.equals("2U")) ||(input.equals("2V"))) {
sign1 = sign1 * -1;
}
else {
sign1=1;
}
return sign1;
}
public static void OFF() {
System.exit(0);
}
public static void solve() {
}
}
Where do I go from here? I'm stuck in many places. Can someone guide me? First, I'm having problems with the methods. I used a couple of methods to display the "Panther Solver" and get the input.
The assignment asks to display the "Panther Solve", then the user picks what digits he/she wants. IE "32" means 2. This is very tricky though. If the user selects the +/- sign before a digit, it changes the value that he/she is about the input to a negative. It however does NOT display the negative sign right away, but only after he/she selects the digits.
Each time you select the digit and press enter, the screen pretty much reloads itself, and in the answer key, it displays what you typed. In the "0", row, it also displays what you just selected.
If you select the +/- sign after a digit is selected, nothing will happen. If you select any valid key that does not correlate to an input, nothing should happen. Just like the quadratic equation, with a,b,c, you type in your first response (a), then input comma, then go to b, then comma, then c, then solve. Each time you input, the input is evaluated.
In the input, all letters must be capitalized, if required, or else you would return and "Invalid Key". Also, for the equation, if a=0, return "Error".
I also have to formulate a solution for imaginary numbers, using i.
I am stuck in all parts. My questions are, where do I go from here in my code.
My first problem is getting the "Panther Solver" to display first, then accept the input. The next one is evaluated the negative/positive sign, and if it comes after or before the number. If it comes after, do nothing. If before, change the value to negative.
The other one is trying to make a loop for all of this in the main statement. Because for "a" in the quadratic equation, the user could want to enter "100". So I have to loop that.
Last, on the "0" row, I have to display the previous user input, just like an actual calculator. I'm having trouble getting that, and making it fit. For example, "a" starts at two spaces from the enter. Obviously as much input is entered, "a" moves to the left.
Thanks
Like all beginners, you're making the problem too difficult by failing to decompose it into small enough chunks.
Forget about user input and interfaces. Get the base solver algorithm working with hard wired inputs that you know the answer to. Write it, test it, and put it aside. Then start developing another class that deals only with getting input values and passing them to the class that actually does the work.
When you find yourself overwhelmed by too much detail, simplify the problem into smaller parts that you can deal with. Then knit them together to solve your larger problem.
It's call decomposition. It's the basis for all problem solving, especially programming and computer science.
For goodness' sake, it's solving a quadratic equation. Panther? Unnecessarily confusing.
Don't be fooled by the name. Forget about all that fancy output and get the base solver working. There are special cases you'll need to concern yourself with:
Two real roots.
One zero root, one real root.
Two complex conjugate roots.

Redundant code constructs

The most egregiously redundant code construct I often see involves using the code sequence
if (condition)
return true;
else
return false;
instead of simply writing
return (condition);
I've seen this beginner error in all sorts of languages: from Pascal and C to PHP and Java. What other such constructs would you flag in a code review?
if (foo == true)
{
do stuff
}
I keep telling the developer that does that that it should be
if ((foo == true) == true)
{
do stuff
}
but he hasn't gotten the hint yet.
if (condition == true)
{
...
}
instead of
if (condition)
{
...
}
Edit:
or even worse and turning around the conditional test:
if (condition == false)
{
...
}
which is easily read as
if (condition) then ...
Using comments instead of source control:
-Commenting out or renaming functions instead of deleting them and trusting that source control can get them back for you if needed.
-Adding comments like "RWF Change" instead of just making the change and letting source control assign the blame.
Somewhere I’ve spotted this thing, which I find to be the pinnacle of boolean redundancy:
return (test == 1)? ((test == 0) ? 0 : 1) : ((test == 0) ? 0 : 1);
:-)
Redundant code is not in itself an error. But if you're really trying to save every character
return (condition);
is redundant too. You can write:
return condition;
Declaring separately from assignment in languages other than C:
int foo;
foo = GetFoo();
Returning uselessly at the end:
// stuff
return;
}
I once had a guy who repeatedly did this:
bool a;
bool b;
...
if (a == true)
b = true;
else
b = false;
void myfunction() {
if(condition) {
// Do some stuff
if(othercond) {
// Do more stuff
}
}
}
instead of
void myfunction() {
if(!condition)
return;
// Do some stuff
if(!othercond)
return;
// Do more stuff
}
Using .tostring on a string
Putting an exit statement as first statement in a function to disable the execution of that function, instead of one of the following options:
Completely removing the function
Commenting the function body
Keeping the function but deleting all the code
Using the exit as first statement makes it very hard to spot, you can easily read over it.
Fear of null (this also can lead to serious problems):
if (name != null)
person.Name = name;
Redundant if's (not using else):
if (!IsPostback)
{
// do something
}
if (IsPostback)
{
// do something else
}
Redundant checks (Split never returns null):
string[] words = sentence.Split(' ');
if (words != null)
More on checks (the second check is redundant if you are going to loop)
if (myArray != null && myArray.Length > 0)
foreach (string s in myArray)
And my favorite for ASP.NET: Scattered DataBinds all over the code in order to make the page render.
Copy paste redundancy:
if (x > 0)
{
// a lot of code to calculate z
y = x + z;
}
else
{
// a lot of code to calculate z
y = x - z;
}
instead of
if (x > 0)
y = x + CalcZ(x);
else
y = x - CalcZ(x);
or even better (or more obfuscated)
y = x + (x > 0 ? 1 : -1) * CalcZ(x)
Allocating elements on the heap instead of the stack.
{
char buff = malloc(1024);
/* ... */
free(buff);
}
instead of
{
char buff[1024];
/* ... */
}
or
{
struct foo *x = (struct foo *)malloc(sizeof(struct foo));
x->a = ...;
bar(x);
free(x);
}
instead of
{
struct foo x;
x.a = ...;
bar(&x);
}
The most common redundant code construct I see is code that is never called from anywhere in the program.
The other is design patterns used where there is no point in using them. For example, writing "new BobFactory().createBob()" everywhere, instead of just writing "new Bob()".
Deleting unused and unnecessary code can massively improve the quality of the system and the team's ability to maintain it. The benefits are often startling to teams who have never considered deleting unnecessary code from their system. I once performed a code review by sitting with a team and deleting over half the code in their project without changing the functionality of their system. I thought they'd be offended but they frequently asked me back for design advice and feedback after that.
I often run into the following:
function foo() {
if ( something ) {
return;
} else {
do_something();
}
}
But it doesn't help telling them that the else is useless here. It has to be either
function foo() {
if ( something ) {
return;
}
do_something();
}
or - depending on the length of checks that are done before do_something():
function foo() {
if ( !something ) {
do_something();
}
}
From nightmarish code reviews.....
char s[100];
followed by
memset(s,0,100);
followed by
s[strlen(s)] = 0;
with lots of nasty
if (strcmp(s, "1") == 0)
littered about the code.
Using an array when you want set behavior. You need to check everything to make sure its not in the array before you insert it, which makes your code longer and slower.
Redundant .ToString() invocations:
const int foo = 5;
Console.WriteLine("Number of Items: " + foo.ToString());
Unnecessary string formatting:
const int foo = 5;
Console.WriteLine("Number of Items: {0}", foo);

Algorithm to format text to Pascal or camel casing

Using this question as the base is there an alogrithm or coding example to change some text to Pascal or Camel casing.
For example:
mynameisfred
becomes
Camel: myNameIsFred
Pascal: MyNameIsFred
I found a thread with a bunch of Perl guys arguing the toss on this question over at http://www.perlmonks.org/?node_id=336331.
I hope this isn't too much of a non-answer to the question, but I would say you have a bit of a problem in that it would be a very open-ended algorithm which could have a lot of 'misses' as well as hits. For example, say you inputted:-
camelCase("hithisisatest");
The output could be:-
"hiThisIsATest"
Or:-
"hitHisIsATest"
There's no way the algorithm would know which to prefer. You could add some extra code to specify that you'd prefer more common words, but again misses would occur (Peter Norvig wrote a very small spelling corrector over at http://norvig.com/spell-correct.html which might help algorithm-wise, I wrote a C# implementation if C#'s your language).
I'd agree with Mark and say you'd be better off having an algorithm that takes a delimited input, i.e. this_is_a_test and converts that. That'd be simple to implement, i.e. in pseudocode:-
SetPhraseCase(phrase, CamelOrPascal):
if no delimiters
if camelCase
return lowerFirstLetter(phrase)
else
return capitaliseFirstLetter(phrase)
words = splitOnDelimiter(phrase)
if camelCase
ret = lowerFirstLetter(first word)
else
ret = capitaliseFirstLetter(first word)
for i in 2 to len(words): ret += capitaliseFirstLetter(words[i])
return ret
capitaliseFirstLetter(word):
if len(word) <= 1 return upper(word)
return upper(word[0]) + word[1..len(word)]
lowerFirstLetter(word):
if len(word) <= 1 return lower(word)
return lower(word[0]) + word[1..len(word)]
You could also replace my capitaliseFirstLetter() function with a proper case algorithm if you so wished.
A C# implementation of the above described algorithm is as follows (complete console program with test harness):-
using System;
class Program {
static void Main(string[] args) {
var caseAlgorithm = new CaseAlgorithm('_');
while (true) {
string input = Console.ReadLine();
if (string.IsNullOrEmpty(input)) return;
Console.WriteLine("Input '{0}' in camel case: '{1}', pascal case: '{2}'",
input,
caseAlgorithm.SetPhraseCase(input, CaseAlgorithm.CaseMode.CamelCase),
caseAlgorithm.SetPhraseCase(input, CaseAlgorithm.CaseMode.PascalCase));
}
}
}
public class CaseAlgorithm {
public enum CaseMode { PascalCase, CamelCase }
private char delimiterChar;
public CaseAlgorithm(char inDelimiterChar) {
delimiterChar = inDelimiterChar;
}
public string SetPhraseCase(string phrase, CaseMode caseMode) {
// You might want to do some sanity checks here like making sure
// there's no invalid characters, etc.
if (string.IsNullOrEmpty(phrase)) return phrase;
// .Split() will simply return a string[] of size 1 if no delimiter present so
// no need to explicitly check this.
var words = phrase.Split(delimiterChar);
// Set first word accordingly.
string ret = setWordCase(words[0], caseMode);
// If there are other words, set them all to pascal case.
if (words.Length > 1) {
for (int i = 1; i < words.Length; ++i)
ret += setWordCase(words[i], CaseMode.PascalCase);
}
return ret;
}
private string setWordCase(string word, CaseMode caseMode) {
switch (caseMode) {
case CaseMode.CamelCase:
return lowerFirstLetter(word);
case CaseMode.PascalCase:
return capitaliseFirstLetter(word);
default:
throw new NotImplementedException(
string.Format("Case mode '{0}' is not recognised.", caseMode.ToString()));
}
}
private string lowerFirstLetter(string word) {
return char.ToLower(word[0]) + word.Substring(1);
}
private string capitaliseFirstLetter(string word) {
return char.ToUpper(word[0]) + word.Substring(1);
}
}
The only way to do that would be to run each section of the word through a dictionary.
"mynameisfred" is just an array of characters, splitting it up into my Name Is Fred means understanding what the joining of each of those characters means.
You could do it easily if your input was separated in some way, e.g. "my name is fred" or "my_name_is_fred".

Resources