N/A Interview Question
Software Engineer in TestsCountry: India
Interview Type: Phone Interview
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "This is a test String!!";
String temp[] = str.split(" ");
String result = null;
for(int i=1; i<=temp.length;i++){
String tempVar = null;
if(i%2 == 0){
for(int j = temp[i-1].length() - 1; j>=0; j--){
tempVar = tempVar + temp[i-1].charAt(j);
}
}
else if(i%2 != 0 || i == 0)
tempVar = temp[i-1].toUpperCase();
result= result + tempVar+" ";
}
System.out.println(result.replace("null", ""));
}
Pretty Straight forward:
public String modify(String orig) {
String[] toModify = orig.split(" ");
StringBuffer out = new StringBuffer();
for (int i = 0; i < toModify.length; i++) {
out.append( (stringIsOdd(toModify[i])) ? capitalize(toModify[i]) : reverse(toModify[i]) );
out.append(" ");
}
return out.toString();
}
public String capitalize(String s) {
return s.toUpperCase();
}
public String reverse(String s) {
StringBuffer out = new StringBuffer();
for (int i = 0; i < out.length(); i++) {
out.append(s.charAt(out.length() - i - 1));
}
return out.toString();
}
public boolean stringIsOdd(String s) {
return (s.length() % 2 == 1);
}
C Code to solve the above problem is as follows
#include <stdio.h>
#include <ctype.h>
int main()
{
char s[10000];
char *p,*q;
gets(s);
p=s; q=s;
int count=1;
while(*p && *q){
if(*q==' '){
q++;
printf(" ");
p=q;
count++;
continue;
}
if(count%2==1){
if(!isupper(*q))
{*q=*q-32;
printf("%c",*q);}
q++;
}
else{
while(*q!=' ' && *q)
q++;
char *preserve=q;
q--;
while(q!=p){
printf("%c",*q);
q--;
}
printf("%c",*q);
q=preserve;
}
}
return 0;
}
public class Odd_upper_even_rev {
public static void main(String args[]){
String str="This is a test string!!";
String finalstr="",arr[]=str.split(" ");
int len=arr.length;
for(int i=0;i<len;i++)
{
if(i%2==0)
{
arr[i]=arr[i].toUpperCase();
}
else
{
StringBuffer sb=new StringBuffer(arr[i]);
StringBuffer temp=sb.reverse();
String s=new String(temp);
arr[i]=s;
}
}
for(int j=0;j<len;j++)
{
finalstr=finalstr+" "+arr[j];
}
System.out.println(finalstr);
}
}
public class Odd_upper_even_rev {
public static void main(String args[]){
String str="This is a test string!!";
String finalstr="",arr[]=str.split(" ");
int len=arr.length;
for(int i=0;i<len;i++)
{
if(i%2==0)
{
arr[i]=arr[i].toUpperCase();
}
else
{
StringBuffer sb=new StringBuffer(arr[i]);
StringBuffer temp=sb.reverse();
String s=new String(temp);
arr[i]=s;
}
}
for(int j=0;j<len;j++)
{
finalstr=finalstr+" "+arr[j];
}
System.out.println(finalstr);
}
}
public class Odd_upper_even_rev {
public static void main(String args[]){
String str="This is a test string!!";
String finalstr="",arr[]=str.split(" ");
int len=arr.length;
for(int i=0;i<len;i++)
{
if(i%2==0)
{
arr[i]=arr[i].toUpperCase();
}
else
{
StringBuffer sb=new StringBuffer(arr[i]);
StringBuffer temp=sb.reverse();
String s=new String(temp);
arr[i]=s;
}
}
for(int j=0;j<len;j++)
{
finalstr=finalstr+" "+arr[j];
}
System.out.println(finalstr);
}
}
O(n) solution in python:
def format_words(statement):
words = statement.split(" ")
output = []
for word in words:
if len(word)%2 == 0:
x = ""
for i in range(len(word) - 1, -1, -1):
x += word[i]
output.append(x)
else:
output.append(word.upper())
for word in output:
print "{}".format(word),
Due to the constraint that all chars in the input string may need alteration,
we are stuck with having to assume that a string like
"abcd efgh ijkl mnop qrst uvwx yz" would have to reverse every word in the input and
take O(n) time where n is number of chars total in the string.
A constant space solution would simply reassign the statement to a array of words split by spaces,
then operate on each word, with reversals being done in-place.
public String convert(String target) {
char [] chs = target.toCharArray() ;
int count = 0 ;
int j = 0 ;
for (int i = 0 ; i <= chs.length ;++i) {
if (i == chs.length || i > 0 && (chs[i] == ' ' || !Character.isLetterOrDigit(chs[i])) && Character.isLetterOrDigit(chs[i - 1])) {
while (j < chs.length && !Character.isLetterOrDigit(chs[j])) {
j++;
}
if (j <= i) {
if (count % 2 == 0) {
toUpper (j, i - 1 , chs);
} else {
reverse (j, i - 1, chs) ;
}
j = i ;
count++;
}
}
}
return new String (chs) ;
}
private void reverse (int i , int j , char [] chs){
for (; i < j ; ++i , --j) {
char tmp = chs[i] ;
chs[i] = chs[j] ;
chs[j] = tmp ;
}
}
private void toUpper (int i , int j , char [] chs) {
for (int n = i ; n <= j ; ++n) {
chs[n] = Character.toUpperCase(chs[n]) ;
}
}
var inString = "This is a test String!!";
var outString = "";
//Split
var tokens = inString.split(' ');
//Iterate
var alternator = false;
for(var i = 0; i < tokens.length; i++){
var word;
if(!alternator){
word = capitalize(tokens[i]);
outString = build(outString, word);
alternator = !alternator;
}
else{
word = reverse(tokens[i]);
outString = build(outString, word);
alternator = !alternator;
}
}
//Show results
console.log(outString);
//Capitalize
function capitalize(inToken){
return inToken.toUpperCase();
}
//Reverse
function reverse(inToken){
var stringArray = inToken.split('');
var reverseString = stringArray.reverse();
return reverseString.join('');
}
//Build
function build(inString, inNewToken){
return inString + ' ' + inNewToken;
}
JavaScript:
var inString = "This is a test String!!";
var outString = "";
//Split
var tokens = inString.split(' ');
//Iterate
var alternator = false;
for(var i = 0; i < tokens.length; i++){
var word;
if(!alternator){
word = capitalize(tokens[i]);
outString = build(outString, word);
alternator = !alternator;
}
else{
word = reverse(tokens[i]);
outString = build(outString, word);
alternator = !alternator;
}
}
//Show results
console.log(outString);
//Capitalize
function capitalize(inToken){
return inToken.toUpperCase();
}
//Reverse
function reverse(inToken){
var stringArray = inToken.split('');
var reverseString = stringArray.reverse();
return reverseString.join('');
}
//Build
function build(inString, inNewToken){
return inString + ' ' + inNewToken;
}
String str="this is a test string";
String arr[]=str.split(" ");
for (int i = 0; i < arr.length; i++) {
if (i%2==0) {
arr[i]=arr[i].replace(arr[i], arr[i].toUpperCase());
}else{
StringBuffer sb=new StringBuffer(arr[i]).reverse();
arr[i]=arr[i].replace(arr[i], sb);
}
}
System.out.println(Arrays.toString(arr));
}
public class StringUpperReverse {
public static String oddsUpperEvenReverse(String s){
//put the words into an array using space as the delimiter and
//don't omit trailing spaces
int size = s.split(" ", -1).length;
String[] words = new String[size];
words = s.split(" ", -1);
//this will hold the number of the each word in the string
int wordCount=0;
for(int i=0; i<size; i++){
//don't take spaces into account when counting the words
//and if spaces are encountered do nothing
if(words[i].equals(""))
continue;
else
wordCount++;
//convert the odd words to upper-case
if((wordCount)%2!=0){
words[i] = words[i].toUpperCase();
}
//and reverse the even
else{
words[i] = reverse(words[i]);
}
}
StringBuilder sb = new StringBuilder("");
//replace the spaces that were lost since they were used as delimiters
for(String word: words){
sb.append(word + " ");
}
//remove the last space that was not there initially
return sb.toString().substring(0,sb.toString().length()-1);
}
//helper method to reverse the even strings
private static String reverse(String s)
{
if(s.length()==0)
return s;
else return s.charAt(s.length()-1) + reverse(s.substring(0,s.length()-1));
}
public static void main(String args[]){
String s = " My name is Gabriel and career cup challenges are awesome! ";
System.out.println(oddsUpperEvenReverse(s));
}
}
Java code to solve the problem:
public class StringUpperReverse {
public static String oddsUpperEvenReverse(String s){
//put the words into an array using space as the delimiter and
//don't omit trailing spaces
String[] words = s.split(" ", -1);
//this will hold the number of the each word in the string
int wordCount=0;
for(int i=0; i<words.length; i++){
//don't take spaces into account when counting the words
//and if spaces are encountered do nothing
if(words[i].equals(""))
continue;
else
wordCount++;
//convert the odd words to upper-case
if((wordCount)%2!=0){
words[i] = words[i].toUpperCase();
}
//and reverse the even
else{
words[i] = reverse(words[i]);
}
}
StringBuilder sb = new StringBuilder("");
//replace the spaces that were lost since they were used as delimiters
for(String word: words){
sb.append(word + " ");
}
//remove the last space that was not there initially
return sb.toString().substring(0,sb.toString().length()-1);
}
//helper method to reverse the even strings
private static String reverse(String s)
{
if(s.length()==0)
return s;
else return s.charAt(s.length()-1) + reverse(s.substring(0,s.length()-1));
}
public static void main(String args[]){
String s = " My name is Gabriel and career cup challenges are awesome! ";
System.out.println(oddsUpperEvenReverse(s));
}
}
void ModifyString(char* inputString);
void UpperWord(char* inputString, char* startChar, char* endChar);
void ReverseWord(char* inputString, char* startChar, char* endChar);
void ModifyString(char* inputString)
{
char* startChar = inputString;
char* endChar = startChar;
bool isOddWord = true;
// Walk the string
while (1)
{
// If we found the end of a word
if (*endChar == ' ' || *endChar == '\0')
{
// Make word upper case
if (isOddWord)
UpperWord(inputString, startChar, endChar);
// Reverse string, not including the word ending character
else
ReverseWord(inputString, startChar, endChar - 1);
isOddWord = !isOddWord;
// Set our new start character, skipping over the ending character of space or null
startChar = endChar + 1;
}
// If we hit the end of the string then exit
if (*endChar == '\0')
break;
// Otherwise skip over our space character
else
endChar++;
}
}
void UpperWord(char* inputString, char* startChar, char* endChar)
{
// Convert the string not including the ending character (space or null)
while (startChar != endChar)
{
// If this is a letter and it is lowercase
if (*startChar >= 'a' && *startChar <= 'z')
{
*startChar = 'A' + (*startChar % 'a');
}
startChar++;
}
}
void ReverseWord(char* inputString, char* startChar, char* endChar)
{
while (startChar < endChar)
{
char swapChar = *endChar;
*endChar = *startChar;
*startChar = swapChar;
startChar++;
endChar--;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
char inputString[] = "This is a test String!!";
ModifyString(inputString);
cout << inputString << endl;
return 0;
}
public String reverseEvenStringUppercaseOddString(String str) {
int count = 0;
int wordCount = 0;
String revString = "";
String output = "";
for(int i = 0; i < str.length(); i++) {
if(str.charAt(i) != ' ') {
revString = str.charAt(i) + revString;
count++;
} else {
if(count > 0) {
wordCount++;
if(wordCount % 2 == 0) {
output = output + revString;
} else {
output = output + str.substring(i - count, i).toUpperCase();
}
}
revString = "";
count = 0;
output = output + str.charAt(i);
}
}
if(count > 0) {
wordCount++;
if(wordCount % 2 == 0) {
output = output + revString;
} else {
output = output + str.substring(str.length() - count, str.length()).toUpperCase();
}
}
return output;
}
//Below code is in C#
public static void ConvertOddWordsToUpperAndReverseEvenWords(string inputString)
{
int wordPosition = 1;
string temp = string.Empty;
char delimeter = ' ';
StringBuilder sb = new StringBuilder();
for (int counter = 0; counter <= inputString.Length - 1; counter++)
{
if (inputString[counter] != delimeter && counter != inputString.Length -1)
{
temp += inputString[counter];
}
else
{
if (wordPosition % 2 == 1)
{
sb.Append(temp.ToUpper()).Append(delimeter);
}
else
{
sb.Append(ReverseWord(temp)).Append(delimeter);
}
temp = string.Empty;
wordPosition++;
}
}
Console.WriteLine("Input string: {0}", inputString);
Console.WriteLine("Output String: {0}", sb.ToString());
Console.ReadLine();
}
private static string ReverseWord(string word)
{
StringBuilder sb = new StringBuilder();
for (int i = word.Length - 1; i >= 0; i--)
{
sb.Append(word[i]);
}
return sb.ToString();
}
public class StringAlgo {
private static String str = "This is test String";
private static String resultStr = "";
public static void main(String[] args) {
StringTokenizer strToken = new StringTokenizer(str);
int len = strToken.countTokens();
String arr[] = new String[len];
int i = 1,j=0;
while(strToken.hasMoreTokens())
{
if(i%2==1)
{
arr[j]= strToken.nextToken().toUpperCase();
}
else
{
String strEven = strToken.nextToken();
StringBuilder sb = new StringBuilder(strEven).reverse();
arr[j] = sb.toString();
}
i++;
j++;
}
for(int k = 0;k<arr.length;k++)
{
if(k==0)
{
resultStr = arr[k];
}
else{
resultStr = resultStr+" "+arr[k];
}
}
System.out.println("The final String is "+resultStr);
}
}
input_string = "This is a Test String input"
def reverse(words : []):
if len(words) == 0:
return ""
else:
first = words[0]
words.pop(0)
return first[::-1] + " " + toupper(words)
def toupper(words : []):
if len(words) == 0:
return ""
else:
first = words[0]
words.pop(0)
return first.upper() + " " + reverse(words)
words = input_string.split(" ")
print (toupper(words))
input_string = "This is a Test String input"
def reverse(words : []):
if len(words) == 0:
return ""
else:
first = words[0]
words.pop(0)
return first[::-1] + " " + toupper(words)
def toupper(words : []):
if len(words) == 0:
return ""
else:
first = words[0]
words.pop(0)
return first.upper() + " " + reverse(words)
words = input_string.split(" ")
print (toupper(words))
public static String uppercaseAndReverseAlternately(String str) {
if (str.length() == 0 || str == null) {
return null;
}
String out = "";
String temp = "";
int count = 0;
int i = 0;
while (i < str.length()) {
if (str.charAt(i) == ' ') {
out = out + str.charAt(i);
i++;
} else {
while (i < str.length() && str.charAt(i) != ' ') {
if (count % 2 == 0) {
temp = temp + (str.charAt(i) + "").toUpperCase();
} else {
temp = str.charAt(i) + temp;
}
i++;
}
out = out + temp;
count++;
temp = "";
}
}
return out;
}
public class Revers_String_Homework1 {
public static void main(String[] args) {
String str1 = "hi bob how are you";
String Rstr1 = Rstr(str1);
System.out.println(Rstr1);
}
private static String Rstr (String str1){
String reversStr = "";
String[] Arrey2 = str1.split("\\s+");
for( int i= 0; i<Arrey2.length; i++){
if( i %2 == 0 ){
Arrey2[i]= Arrey2[i].replace(Arrey2[i], Arrey2[i].toUpperCase());
}
reversStr= reversStr+" "+ Arrey2[i];
}
return reversStr;
}
}
and
public class Ex_modify_TestString {
public static void main(String[] args) {
String str1 = "hi bob how are you";
String Rstr1 = Rstr(str1);
System.out.println(Rstr1);
}
private static String Rstr(String str1) {
String reversStr = "";
String[] Arrey2 = str1.split("\\s+");
for (int i = 0; i < Arrey2.length; i++) {
if (i % 2 == 0) {
Arrey2[i] = Arrey2[i].replace(Arrey2[i], Arrey2[i].toUpperCase());
}
reversStr = reversStr + " " + Arrey2[i];
}
return reversStr;
}
}
public class Ex_modify_TestString {
public static void main(String[] args) {
String str1 = "hi bob how are you";
String Rstr1 = Rstr(str1);
System.out.println(Rstr1);
}
private static String Rstr(String str1) {
String reversStr = "";
String[] Arrey2 = str1.split("\\s+");
for (int i = 0; i < Arrey2.length; i++) {
if (i % 2 == 0) {
Arrey2[i] = Arrey2[i].replace(Arrey2[i], Arrey2[i].toUpperCase());
}
reversStr = reversStr + " " + Arrey2[i];
}
return reversStr;
}
}
//C# code
string[] input = "This is a test String!!".Split(' ');
string inputword = string.Empty;
string reverseword = string.Empty;
string output = string.Empty;
string word = string.Empty;
for (int i = 0; i < input.Length; i++)
{
if (i % 2 == 0)
{
output = output + " " + input[i].ToUpper();
}
else
{
word = input[i];
foreach (var item in word)
{
reverseword = item + "" + reverseword;
}
output = output + " " + reverseword;
}
reverseword = string.Empty;
}
Console.WriteLine(output.Trim());
Console.ReadLine();
In python:
x=input("Please give an sentence:")
def format_word(statement):
words_array=statement.split()
output=[]
for i in range(0,len(words_array)):
if i % 2 ==0:
output.append(words_array[i].upper())
else:
out=''
in_value=words_array[i]
for i in in_value:
out=i+out
output.append(out)
return (' '.join(output))
format_word(x)
So there are multiple spaces in the input string, but here is not getting displayed and are trimmed.
- qe.expert March 18, 2015