How to make last word uppercase in C#? - c#

How can I print by reading the names and surnames from the keyboard and making only the surname letters large?
string name;
Console.Write("Name and surname:");
name=Console.ReadLine();
int word= name.LastIndexOf(" ");
Console.WriteLine(name.Substring(word).ToUpper());
I could write on surname but I could not add name.Sorry my english..

I would use .Split() to separate first and last name
Console.Write("Name and surname:");
string name = Console.ReadLine();
Console.WriteLine(name.Split().First().ToUpper());
Console.WriteLine(name.Split().Last().ToUpper());
if you want to stay with Substring() this would be the approach
Console.Write("Name and surname:");
string name = Console.ReadLine();
int word = name.LastIndexOf(" ");
Console.WriteLine(name.Substring(word+1).ToUpper());
Console.WriteLine(name.Substring(0, word).ToUpper());

I solve my problem.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;/*Add this library for ToTitleCase*/
namespace String_denemeler
{
class Program
{
public static string ToTitleCase(string Text)/*And Add this for ToTitleCase*/
{
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Text);
}
static void Main(string[] args)
{
string name;
Console.Write("Name&Surname:");
name = Console.ReadLine();
name= ToTitleCase(name);
int index = name.LastIndexOf(" ");
Console.WriteLine(name.Substring(0, index) + name.Substring(index).ToUpper());
}
}
}

Related

C# Objects in a list are overwriting each other [duplicate]

This question already has answers here:
What does the static keyword mean?
(4 answers)
Closed 7 years ago.
The code I am looking at is as follows
string data;
string[] tokens;
while (sr.EndOfStream != true)
{
data = sr.ReadLine();
char delim = ',';
tokens = data.Split(delim);
Team t = new Team(tokens[0], int.Parse(tokens[1]), int.Parse(tokens[2]));
TeamList.Add(t);
}
//Test to make sure the teams were stored properly
foreach(Team t in TeamList)
{
Console.WriteLine(t.Name);
}
sr.Close();
When I use the foreach loop to write the team names out it displays 9 copies of Team9 (The teams are listed 1-9 in the text file line by line, with two numbers separated by commas to hold the wins and losses for each team, which is the reason there are delims with commas). This goes for any number of teams I add, if i add a 10th team it does 10 copies of team10, and if I use 8 teams it shows 8 copies of Team8. I added the foreach loop into the while loop to have it show the teams at each stage and it keeps overwriting all previous objects when it creates a new one, so for example the first time it runs the loop it shows Team1, then the next time it runs the loop it shows two lines of Team2, and so on. From my research I saw that this is usually caused by not declaring a new object inside of the loop, but in this case a new object is declared inside the loop.
Edit: the Team class is as follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApplication2
{
class Team
{
private static string tn;
private static int Wins, Losses;
public Team()
{
}
public Team(string name, int wins, int losses)
{
tn = name;
Wins = wins;
Losses = losses;
}
public override string ToString()
{
return tn + ", wins: " + Wins + ", losses: " + Losses;
}
public string Name
{
get { return tn; }
}
}
}
The TeamList variable and main class are as follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
private static Random pick = new Random();
private static List<Team> TeamList = new List<Team>();
static void Main(string[] args)
{
//Reading file io
Schedule(TeamList);
Console.ReadLine();
}
static void Schedule(List<Team> TeamList)
{
StreamReader sr = new StreamReader("C:/Users/andre/Desktop/VisualStudioProjects/ConsoleApplication1/ConsoleApplication1/TeamList.txt");
string data;
string[] tokens;
while (sr.EndOfStream != true)
{
data = sr.ReadLine();
char delim = ',';
tokens = data.Split(delim);
Team t = new Team(tokens[0], int.Parse(tokens[1]), int.Parse(tokens[2]));
TeamList.Add(t);
foreach(Team x in TeamList)
{
Console.WriteLine(x.Name);
}
}
//Test to make sure the teams were stored properly
foreach(Team t in TeamList)
{
Console.WriteLine(t.Name);
}
sr.Close();
}
The text file is simply a file that contains the following
Team1,0,0
Team2,0,0
Team3,0,0
Team4,0,0
Team5,0,0
Team6,0,0
Team7,0,0
Team8,0,0
Team9,0,0
You have
class Team
{
private static string tn; //STATIC??
private static int Wins, Losses; //STATIC??
}
static means the variable is shared between all instances of Team in your application. Remove it please. That is the problem.

Automatic number insertion in MySQL with the format "AN-00000000"

My purpose on this is to insert a autonumber for this format AN-00000000 to the db, with the type in db varchar.
my code in windows form is saving a integer number already "10000000".
But I turn on my mind and think if possible that the auto number will be like this AN-00000000 and to save to the db with a character string.
I tried my best to change and apply but suddenly I can not implement because is on the integer part.
I am creating the basic system in our company to create a automate membership for the members, in our company we have 4 parts of membership which is Dep, sep, mep and cef, so I turn on my mind that i need to implement the 4 Id with the following to identify what the department they included. like DEP-00000001, SEP-00000001, MEP-0000001 and CEF-00000001.
Can anyone suggest or give their opinion on my code below? Thanks!
DBconnect.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
using System.Data;
namespace PAIRDevelopment.Classes
{
public class DBConnect
{
public static string csConnect = "uid=root; database=membership; pooling = false; convert zero datetime=True";
public static MySqlConnection csCon= new MySqlConnection(Classes.DBConnect.csConnect);
public MySqlCommand cmdCon = new MySqlCommand();
public MySqlDataReader reader;
public void nonQuery(string cmdText)
{
cmdCon.Connection = csCon;
csCon.Open();
cmdCon.CommandText = cmdText;
cmdCon.ExecuteNonQuery();
cmdCon.Dispose();
csCon.Close();
}
public void OPEN(string cmdtext)
{
cmdCon.Connection = Classes.DBConnect.csCon;
Classes.DBConnect.csCon.Open();
cmdCon.CommandText = cmdtext;
reader = cmdCon.ExecuteReader();
}
public void CLOSE()
{
reader.Close();
cmdCon.Dispose();
Classes.DBConnect.csCon.Close();
}
}
}
Windows Form:
using System;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace PAIRDevelopment
{
public partial class Pair_Individual : Form
{
Classes.DBConnect OpenConCls = new Classes.DBConnect();
public Pair_Individual()
{
InitializeComponent();
textBox6.MaxLength = 13;
}
private void benabled_Click(object sender, EventArgs e)
{
OpenConCls.OPEN("SELECT MAX(piId) FROM tblpair_individual_membership");
while (OpenConCls.reader.Read())
{
string pcount = OpenConCls.reader[0].ToString();
if (pcount.Length == 0)
{
textBox1.Text = "10000000";
}
else
{
//int pcount1 = Convert.ToInt32(pcount);
//int pcountAdd = pcount1 + 1;
int pcount1 = Convert.ToInt32(pcount);
int pcountAdd = pcount1 + 1;
textBox1.Text = pcountAdd.ToString();
}
}
OpenConCls.CLOSE();
}
int pcount1 = Convert.ToInt32(pcount);
You are probably throwing a FormatException on the above line now if the string contains more than 0-9.
FormatException - value does not consist of an optional sign followed by
a sequence of digits (0 through 9).
If you know the first 4 chars will always be "XXX-" (e.g. "MEP-") then why don't you:
int pcount1 = Convert.ToInt32(pcount.Substring(4)); // ######## part
int pcountAdd = pcount1 + 1; // ######## + 1
textBox1.Text = String.Format("{0}-{1:D8}", pcount.Substring(0, 4), pcountAdd);
Which will convert only the numeric part, increment it, and then concatenate it with the first part.
Also you can look into the TryParse method. Which will indicate if your parse succeeded.
TryParse - Converts the string representation of a number to its 32-bit signed
integer equivalent. A return value indicates whether the operation succeeded.

find images url inside string

my program is intended to search for images url inside a string according to specific keywords. it actually works fine, only problem is the "search not found" error.
for some reason its like the code doesn't get to this "if" and wont return any error if there is no match found (last if).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Text.RegularExpressions;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
using (WebClient client = new WebClient())
{
int count = 0;
Regex SearchItem = new Regex("http://.+?\\.jpg");
string SearchValue = "fgdfgdf";
string htmlCode = "fsdflkjsdfkjsdfkjdsflkhttp://www.dssdtanya.jpgfsdf;ldsmfs;dlfms;dmfs";
Match matches = SearchItem.Match(htmlCode);
while (matches.Success)
{
string test = matches.ToString();
if (test.Contains(SearchValue))
{
count++;
Console.WriteLine("Result #{0}: '{1}' found in the source code at position {2}.",count, matches.Value, matches.Index);
matches = matches.NextMatch();
}
}
Console.WriteLine(count);
if (count == 0) { Console.WriteLine("search not found."); }
Console.ReadKey();
}
}
}
}
Your program enters an infinite loop if the first test doesn't contain the search value. Change your code to this:
while (matches.Success)
{
string test = matches.ToString();
if (test.Contains(SearchValue))
{
count++;
Console.WriteLine("Result #{0}: '{1}' found in the source code at position {2}.", count, matches.Value, matches.Index);
}
matches = matches.NextMatch(); //moved this outside the if
}

How to use BinaryReader in loop so I can display chunks of information in correct format?

I am doing homework and I got to the part where I need to display my data from data file. The problem is that I can display individual data by using BinaryReader() but I can not create a correct loop which would display all data in format specified below:
Enter Book Title: Title 1
Enter Author's First Name: First 1
Enter Author's Last Name: Last 1
Enter Publisher's Name: Publisher 1
Enter Book Price: $1.1
Would like to enter another book? [Y or N] y
Enter Book Title: Title 2
Enter Author's First Name: First 2
Enter Author's Last Name: Last 2
Enter Publisher's Name: Publisher 2
Enter Book Price: $2.2
Would like to enter another book? [Y or N] n
Title 1
Publisher 1
1.1
First 1 Last 1
Title 2
Publisher 2
2.2
First 2 Last 2
Instead, I am showing only the last entry. See the problem? I do not know how to display all data from data folder by using a loop.
I appreciate any tips how this could be done.
Thank You!
Here are my code files:
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Lab_7
{
class Program
{
private const string FILE_NAME = "lab07.dat";
static void Main(string[] args)
{
char ask;
if (!File.Exists(FILE_NAME))
{
FileStream fileStream = new FileStream(FILE_NAME, FileMode.OpenOrCreate);
}
Book book = new Book();
FileStream writeStream = new FileStream(FILE_NAME, FileMode.Append);
BinaryWriter write = new BinaryWriter(writeStream);
do
{
Console.Write("Enter Book Title: ");
book.Title = Console.ReadLine();
Console.Write("Enter Author's First Name: ");
book.AuthorFirstName = Console.ReadLine();
Console.Write("Enter Author's Last Name: ");
book.AuthorLastName = Console.ReadLine();
Console.Write("Enter Publisher's Name: ");
book.PublisherName = Console.ReadLine();
Console.Write("Enter Book Price: $");
book.Price = float.Parse(Console.ReadLine());
Console.Write("Would like to enter another book? [Y or N] ");
ask = char.Parse(Console.ReadLine().ToUpper());
book.saveDataTo(write);
}
while (ask == char.Parse("Y"));
write.Close();
FileStream readStream = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
BinaryReader read = new BinaryReader(readStream);
book.display();
read.Close();
}
}
}
Publication.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Lab_7
{
class Publication
{
private float price;
private string publisherName, title;
public float Price
{
get
{
return price;
}
set
{
price = value;
}
}
public string PublisherName
{
get
{
return publisherName;
}
set
{
publisherName = value;
}
}
public string Title
{
get
{
return title;
}
set
{
title = value;
}
}
public void display()
{
Console.WriteLine("{0}\n{1}\n{2}", title, publisherName, price);
}
}
}
Book.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Lab_7
{
class Book : Publication
{
private string authorFirstName, authorLastName;
public string AuthorFirstName
{
get
{
return authorFirstName;
}
set
{
authorFirstName = value;
}
}
public string AuthorLastName
{
get
{
return authorLastName;
}
set
{
authorLastName = value;
}
}
public new void display()
{
base.display();
Console.WriteLine("{0}", getAuthorName());
}
public string getAuthorName()
{
return authorFirstName + " " + authorLastName;
}
public void readDataFrom(BinaryReader r)
{
base.Price = r.ReadSingle();
base.PublisherName = r.ReadString();
base.Title = r.ReadString();
authorFirstName = r.ReadString();
authorLastName = r.ReadString();
}
public void saveDataTo(BinaryWriter w)
{
w.Write(base.Price);
w.Write(base.PublisherName);
w.Write(base.Title);
w.Write(AuthorFirstName);
w.Write(AuthorLastName);
}
}
}
Thank you for any help.
Regards.
HelpNeeder.
-- EDIT --
Works! Thank you!
while (read.PeekChar() != -1)
{
book.readDataFrom(read);
book.display();
}
Also, I had to make sure that new file is being created each time I ran the program!
Plus I have to make sure that I close my FileStreams because I keep crashing program.
You forget to perform a loop. book.display only shows one book. You also forget to read in data for the book.
You can check if there is more data in the file by doing a peek. If peek returns -1 you know there is no more data.
Example:
FileStream readStream = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
BinaryReader read = new BinaryReader(readStream);
while (read.PeekChar() != -1)
{
book.readDataFrom(read);
book.display();
}
Use binaryReader.PeekChar() method.
while(binaryReader.PeekChar()!=-1)
{
//
}
EDIT:
FileStream readStream = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
BinaryReader read = new BinaryReader(readStream);
Book book = new Book();
while(read.PeekChar()!=-1)
{
book.readDataFrom(read);
book.display();
}

String Matching

I have a string
String mainString="///BUY/SELL///ORDERTIME///RT///QTY///BROKERAGE///NETRATE///AMOUNTRS///RATE///SCNM///";
Now I have another strings
String str1= "RT";
which should be matched only with RT which is substring of string mainString but not with ORDERTIME which is also substring of string mainString.
String str2= "RATE" ;
And RATE(str2) should be matched with RATE which is substring of string mainString but not with NETRATE which is also substring of string mainString.
How can we do that ?
Match against "///RT///" and "///RATE///".
This might give you some clues - no where near real code quality, and only a 5 minute job to come with this shoddy solution but does do what you need. it smells lots be warned.
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
namespace test {
class Program {
static void Main(string[] args) {
String mainString="//BUY/SELL//ORDERTIME//RT//QTY//BROKERAGE//NETRATE//AMOUNTRS//RATE//SCNM//";
Hashtable ht = createHashTable(mainString);
if (hasValue("RA", ht)) {
Console.WriteLine("Matched RA");
} else {
Console.WriteLine("Didnt Find RA");
}
if (hasValue("RATE", ht)) {
Console.WriteLine("Matched RATE");
}
Console.Read();
}
public static Hashtable createHashTable(string strToSplit) {
Hashtable ht = new Hashtable();
int iCount = 0;
string[] words = strToSplit.Split(new Char[] { '/', '/', '/' });
foreach (string word in words) {
ht.Add(iCount++, word);
}
return ht;
}
public static bool hasValue(string strValuetoSearch, Hashtable ht) {
return ht.ContainsValue(strValuetoSearch);
}
}
}
as far as I understand your question you want to match a string between /// as delimiters.
if you look for str you just have to do
Regex.Match(mainString, "(^|///)" + str + "(///|$)");
I don't know it will work every time or not.But I have tried this and it works right now in this string matching. I want to know whether this is ok or not,please give me suggestion.
str1 = str1.Insert(0, "///");
str1=str1.Insert(str1.Length,"///");
bool Result = mainString.Contains(str1);
What about Linq to Object?
String mainString="///BUY/SELL///ORDERTIME///RT///QTY///BROKERAGE///NETRATE///AMOUNTRS///RATE///SCNM///";
String searchTerm = "RT";
String[] src = mainString.split('///');
var match = from word in src where
word.ToLowerInvariant() == searchTerm.ToLowerInvariant()
select word;
I don't have VS near me so I can't test it, but it should be something similar to this.

Categories

Resources