Sunday 22 February 2015

Interview Question of the Week #008 – Write Scripts to Convert String to Title Case or Proper Case


Just received a question in email:
“I just got out of the interview and I was asked to write scripts to convert a string to Title Case. I was also asked to refer to the website over here to validate my answer after I complete writing script.
Do you think it is not fair to ask such questions in an interview?”
Well, this time the question is not about writing scripts, but more about if this kind of questions is a good question for interview or not. The question is a bit open ended and my answer can be vague or full of philosophy of it depends. However, I will try to answer it bit more honest and clear.
I believe all questions are good question in the interview. It is never about the question’s validity, but more about quality of answer and attitude decides the capability of the user. If I ever face a situation where I am asked questions to write script to convert a string to title case, I would happily sit down and attempt to write it if I want the job and I am up for the challenge. If I do not know how to write it, I will honestly say I do not know and let the interviewer decide the next step. If you believe this kind of question is inappropriate for the job which you have applied, well, you can always mention that after you solve it.
Well – in my early career, I have written similar script and I have posted that on this blog post well. You can refer that in this blog post – SQL SERVER – UDF – Function to Convert Text String to Title Case – Proper Case. I strongly suggest that you read the comments as those are packed with the wealth of the information. Here is the script from the blog post.
CREATE FUNCTION udf_TitleCase (@InputString VARCHAR(4000) )RETURNS VARCHAR(4000)AS
BEGIN
DECLARE 
@Index INT
DECLARE 
@Char CHAR(1)DECLARE @OutputString VARCHAR(255)SET @OutputString LOWER(@InputString)SET @Index 2SET @OutputString =STUFF(@OutputString11,UPPER(SUBSTRING(@InputString,1,1)))WHILE @Index <= LEN(@InputString)BEGIN
SET 
@Char SUBSTRING(@InputString@Index1)IF @Char IN (' '';'':''!''?'',''.''_''-''/''&','''','(')IF @Index <= LEN(@InputString)BEGIN
IF 
@Char !''''ORUPPER(SUBSTRING(@InputString@Index 11)) != 'S'SET @OutputString =STUFF(@OutputString@Index 11,UPPER(SUBSTRING(@InputString@Index 11)))END
SET 
@Index @Index 1END
RETURN 
ISNULL(@OutputString,'')END
You can use this script as follows:
SELECT dbo.udf_TitleCase('This function will convert this string to title case!')
Reference: Pinal Dave (http://blog.sqlauthority.com)

No comments:

Post a Comment