Capitalize the last letter of each word in a string - python-3.x

def headAndFoot(s):
"""precondition: s is a string containing lower-case words and spaces
The string s contains no non-alpha characters.
postcondition: For each word, capitalize the first and last letter.
If a word is one letter, just capitalize it. """
last = len(s) - 1
x = s.title()
y = x.split()
return y
What changes do I need to make?

Take a look at my code below and try to use it in the context of your question.
s = 'The dog crossed the street'
result = " ".join([x[:-1].title()+x[len(x)-1].upper() for x in s.split()])
Then result will look like
'ThE DoG CrosseD ThE StreeT'

import java.io.*;
public class ConverT_CapS
{
void main()throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a sentence ");
String str = br.readLine();
str= str.toLowerCase();
StringBuffer sb = new StringBuffer(str);
for(int i=1;i<str.length()-1;i++)
{
if(str.charAt(i+1)==' '||str.charAt(i-1)==' ')
{
char ch= (char)(str.charAt(i)-32);
sb.setCharAt(i,ch);
}
}
sb.setCharAt(0,(char)(str.charAt(0)-32));
sb.setCharAt(str.length()-1,(char)(str.charAt(str.length()-1)-32));
System.out.println(sb);
}
}
input : whats ur name
output: WhatS UR NamE

Related

How to parse a string for numbers and words (strings)? IN JAVA

I have a list of strings that contain names and a series of numbers, ex: "John James Hollywood 1 2 3".
I want to parse out the names using a loop so that I can scan each part of the text and store it in a new string variable. Then I tried to use a conditional to put any numbers in a different variable. I will calculate the average of the numbers and then print the name and the average of the numbers, so the output looks like this:
John James Hollywood: 2
I don't know whether to use the input string stream or what my first steps are.
public static String parseNameNumbers(String text)
{
Scanner scnr = new Scanner(text);
Scanner inSS = null;
int numSum = 0;
int countNum = 0;
String newText = new String();
String sep = "";
while(scnr.hasNext()) {
if(scnr.hasNextInt()) {
numSum = numSum + scnr.nextInt();
countNum++;
}
else {
newText = newText + sep + scnr.next();
sep = " ";
}
}
return newText + ": " + (numSum/countNum);
}

How to concatenate two string in Dart?

I am new to Dart programming language and anyone help me find the best string concatenation methods available in Dart.
I only found the plus (+) operator to concatenate strings like other programming languages.
There are 3 ways to concatenate strings
String a = 'a';
String b = 'b';
var c1 = a + b; // + operator
var c2 = '$a$b'; // string interpolation
var c3 = 'a' 'b'; // string literals separated only by whitespace are concatenated automatically
var c4 = 'abcdefgh abcdefgh abcdefgh abcdefgh'
'abcdefgh abcdefgh abcdefgh abcdefgh';
Usually string interpolation is preferred over the + operator.
There is also StringBuffer for more complex and performant string building.
If you need looping for concatenation, I have this :
var list = ['satu','dua','tiga'];
var kontan = StringBuffer();
list.forEach((item){
kontan.writeln(item);
});
konten = kontan.toString();
Suppose you have a Person class like.
class Person {
String name;
int age;
Person({String name, int age}) {
this.name = name;
this.age = age;
}
}
And you want to print the description of person.
var person = Person(name: 'Yogendra', age: 29);
Here you can concatenate string like this
var personInfoString = '${person.name} is ${person.age} years old.';
print(personInfoString);
Easiest way
String get fullname {
var list = [firstName, lastName];
list.removeWhere((v) => v == null);
return list.join(" ");
}
The answer by Günter covers the majority of the cases of how you would concatenate two strings in Dart.
If you have an Iterable of Strings it will be easier to use writeAll as this gives you the option to specify an optional separator
final list = <String>['first','second','third'];
final sb = StringBuffer();
sb.writeAll(list, ', ');
print(sb.toString());
This will return
'first, second, third'
Let's think we have two strings
String a = 'Hello';
String b = 'World';
String output;
Now we want to concat this two strings
output = a + b;
print(output);
Hello World

Replacing unknown substring?

public static String updatedStr(){
String [] ar= {"green","red","purple","black"};
String str="The colors are (blue), (blue), and (yellow). I prefer (orange)";
I would like a final output string of "The colors are green, red, and purple. I prefer black."
You can do it without using replace. Just iterate over the input String and add to a StringBuilder parts of the original String (that are not contained in parentheses) and the replacement words instead of the parts contained in parentheses.
public static String updatedStr()
{
String [] ar= {"green","red","purple","black"};
String str="The colors are (blue), (blue), and (yellow). I prefer (orange)";
StringBuilder out = new StringBuilder ();
int x = 0;
int pos = 0;
for(int i = str.indexOf('(', 0); i != -1; i = str.indexOf('(', i + 1)) {
out.append (str.substring(pos,i)); // add the part between the last ) and the next (
out.append (ar[x++]); // add replacement word
pos = str.indexOf(')', i) + 1;
}
out.append (str.substring(pos)); // add the part after the final )
return out.toString ();
}
This method returns :
The colors are green, red, and purple. I prefer black
This code makes some simplifying assumptions. For example, the number of elements in the replacements array should be at least as high as the number of words to be replaced. A more complete implementation should contain additional checks.
You can do this by calculating the position of where you are replacing and saving them in an array as follows:
public static String updatedStr(){
String [] ar= {"green","red","purple","black"};
String str="The colors are (blue), (blue), and (yellow). I prefer (orange)";
ArrayList<String> arr = new ArrayList<String>();
int pos [] = new int[ar.length]; // save locations here
for(int i = str.indexOf('(', 0); i != -1; i = str.indexOf('(', i + 1)) {
arr.add(str.substring(i + 1, str.indexOf(')', i)));
pos[arr.size()-1] = i; // save it!
}
// replace from right to left
for (int j=pos.length-1;j>=0;j--){
String newStr = str.substring(0, pos[j]+1) + ar[j] + str.substring(str.indexOf(')',pos[j]+1), str.length());
str = newStr;
}
return str;
}
The trick here is that I'm replacing from right to left so that the positions of where I need to replace do not move when I am replacing them.

Read specific string from each line of text file using BufferedReader in java

my text file :
3.456 5.234 Saturday 4.15am
2.341 6.4556 Saturday 6.08am
At first line, I want to read 3.456 and 5.234 only.
At second line, I want to read 2.341 and 6.4556 only.
Same goes to following line if any.
Here's my code so far :
InputStream instream = openFileInput("myfilename.txt");
if (instream != null) {
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line=null;
while (( line = buffreader.readLine()) != null) {
}
}
Thanks for showing some effort. Try this
while (( line = buffreader.readLine()) != null) {
String[] parts = line.split(" ");
double x = Double.parseDouble(parts[0]);
double y = Double.parseDouble(parts[1]);
}
I typed this from memory, so there might be syntax errors.
int linenumber = 1;
while((line = buffreader.readLine()) != null){
String [] parts = line.split(Pattern.quote(" "));
System.out.println("Line "+linenumber+"-> First Double: "+parts[0]+" Second Double:"
+parts[1]);
linenumber++;
}
The code of Bilbert is almost right. You should use a Pattern and call quote() for the split. This removes all whitespace from the array. Your problem would be, that you have a whitespace after every split in your array if you do it without pattern. Also i added a Linenumber to my output, so you can see which line contains what. It should work fine

When trying to add a space back into a tokenized String, why are two spaces added into my output?

Beginner here. Sorry for the vague title but the code should put my question into perspective.
public static void main(String [] args)
{
String sentence = "hi. how are you! i'm just dandy.";
String tokenSent;
tokenSent = sentenceCapitalizer(sentence);
System.out.println(tokenSent);
}
public static String sentenceCapitalizer(String theSentence)
{
StringTokenizer strTokenizer = new StringTokenizer(theSentence, ".!", true);
String token = null;
String totalToken = "";
String ch = "";
while(strTokenizer.hasMoreTokens())
{
token = strTokenizer.nextToken().trim();
token = token.replace(token.charAt(0), Character.toUpperCase(token.charAt(0)));
StringBuilder str = new StringBuilder(token);
str.append(" ");
totalToken += str;
}
return totalToken;
}
OUTPUT AS IS: Hi . How are you ! I'm just dandy .
I was able to capitalize the first letter of each sentence but I'm wanting the output to keep the same format as the original String. The problem is that it puts a space before and after the ending punctuation. Is there any way to fix this problem using only a StringBuilder and/or StringTokenizer? Thank you for your time.
You can do this.
String delim = ".!";
StringTokenizer strTokenizer = new StringTokenizer(theSentence, delim, true);
Then,
if(delim.contains(token))
str.append(" ");
When you declare new StringTokenizer(theSentence, ".!", true) ,true enables to return delimiter characters also as next token. Since you appending a space to each token, it is normal to get that output.
You can check if the token is a delimiter character, if so, you add the space.
if(token.length() == 1 &&
delims.indexOf(token.charAt(0)) != -1)
str.append(" "); //we just hit the delim char, add space

Resources