Cut off the end of a string - c#

I need to figure out how to remove the end of a string. The only trouble is, the string itself is not set. All I want to keep is the first 3-4 characters in the string.
string Location = "110 - Main Road";
string Location = "123 - Highway";
string Location = "234 - My House";
It could also be;
string Location = "1120 - Main Road";
I know if I can cut it down to the first 4 characters, I can just use .Trim() to remove the white spaces if it is only 3 characters, but I don't know how to cut it down to the first 4 characters?

You can use Split and get your number like this:
string Location = "1120 - Main Road";
int number = int.Parse(Location.Split()[0]);
This should work if there is no white-space before the number.If there is then use StringSplitOptions.RemoveEmptyEntries:
int number = int.Parse(Location.Split(new []{ ' ' },
StringSplitOptions.RemoveEmptyEntries)[0]);

split on spaces, then grab whatever is first, ignore the rest.
string GrabNumber(string input)
{
return input.Split(' ')[0];
}
assuming you want it as an integer you can take it a step further:
int GrabNumber(string input)
{
return int.Parse(input.Split(' ')[0]);
}

You can use String.Split() function to split your string based on delimeter - and then you can convert the first part of the string into integer if you want it in a Integer variable.
Solution 1: if you want to get first part of string as as string.
string Location = "11056 - Main Road";
Location = Location.Split('-')[0].Trim();
Solution 2: if you want to get the first part of the string as integer value.
string Location = "11056 - Main Road";
int num;
int.TryParse(Location.Split('-')[0],out num);

Just use a Substring call with a String.IndexOf, for example
using System;
using System.Collections.Generic;
public class Test
{
public static void Main()
{
List<string> strings = new List<string>();
strings.Add("110 - Main Road");
strings.Add("1104 - Main Road");
strings.Add("11088 - Main Road");
foreach(string s in strings){
Console.WriteLine(s.Substring(0,s.IndexOf("-",0)-1));
}
}
}
That way even if the street number is 4,5,6,7 characters long this will still work

If you just want the first 4 characters you would do this:
Location = Location.Substring(0, 4);
The first argument is the start position and the second argument is the length.

use the substring function of string(startIndex,numberOfCharToKeep) like this:
string Location = "110 - Main Road";
string NewLocation = Location.SubString(0,4);
this keeps your first 4 chars

Depends on how reliable your input is. If you will always have a space after the numbers you can find that location using IndexOf. However, whenever I work with strings I prefer regular expressions. Here is an example of both approaches:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string[] locations =
{
"110 - Main Road",
"123 - Highway",
"234 - My House",
"1120 - Main Road"
};
Regex r = new Regex(#"^\d+");
foreach (string location in locations)
{
Console.WriteLine(location.Substring(0, location.IndexOf(' ')));
Console.WriteLine(r.Match(location).Captures[0].Value);
}
}
}

Related

How do I use .ToUpper or .ToLower on a certain word in a big sentence?

string testSentence = "this is a test sentence and I WANT TO SEE HOW IT WILL LOOK LIKE hoping this part is big";
int firstLetter = testSentence.IndexOf("this");
int length = "this is a test sentence and".Length;
string upperSentence = testSentence.Substring(firstLetter, length).ToUpper();
int secondLetter = testSentence.IndexOf(" I");
int length2 = " I WANT TO SEE HOW IT WILL LOOK LIKE".Length;
string lowerSentence = testSentence.Substring(secondLetter, length2).ToLower();
int thirdSentence = testSentence.IndexOf(" hoping");
int length1 = " hoping this part is big".Length;
string get = testSentence.Substring(thirdSentence, length1).ToUpper();
Console.WriteLine(upperSentence + lowerSentence + get);
Can somebody please tell me how would you capitalize in all big or small letters only one word in the middle of the sentence? For example, make the word ''LOOK'' in small case letters. Does the ''.Length'' call has to be used or is there a different way than literally typing the word or part of the sentence that I want to convert to upper or lower cases?
The problem I have with this is, I cannot isolate just one word and make it low/big letters because then the rest of the string after the particular word is also in the lower/upper cases
In line with #Franck's advice, think about the problem as a human. You have three things:
a sentence
words that you want to be big
words that you want to be small
The sentence can really be broken down into a collection of words (ignoring punctuation). You want to go through the collection of words and change some of them to be uppercase and some of them to be lowercase - all the rest of the words you want to leave as they are.
Here is some code that does this:
using System;
using System.Linq;
public class Program
{
public static void Main()
{
// modify these as you please
string testSentence = "this is a test sentence and I WANT TO SEE HOW IT WILL LOOK LIKE hoping this part is big";
string[] wordsToUpperCase = new string[] { "hoping", "test" };
string[] wordsToLowerCase = new string[] { "look", "is" };
// start processing
// split the sentence into words
string[] wordsInSentence = testSentence.Split(' ');
// a List to hold the reworked words
var outputWords = new System.Collections.Generic.List<string>();
// process the words
foreach (string currentWord in wordsInSentence)
{
// check the wordsToUpperCase array for the current word
bool shouldUpperCaseThisWord = wordsToUpperCase.Any(stringToTest => stringToTest.Equals(currentWord, StringComparison.CurrentCultureIgnoreCase));
// check the wordsToLowerCase array for the current word
bool shouldLowerCaseThisWord = wordsToLowerCase.Any(stringToTest => stringToTest.Equals(currentWord, StringComparison.CurrentCultureIgnoreCase));
// add the current word to the output list
if (shouldUpperCaseThisWord)
outputWords.Add(currentWord.ToUpper());
else if (shouldLowerCaseThisWord)
outputWords.Add(currentWord.ToLower());
else
outputWords.Add(currentWord);
}
string finalOutput = String.Join(" ", outputWords);
Console.WriteLine(finalOutput);
}
}

How to read between a specified character in a string?

I was trying to create a list from a user input with something like this:
Create newlist: word1, word2, word3, etc...,
but how do I get those words one by one only by using commas as references going through them (in order) and placing them into an Array etc? Example:
string Input = Console.ReadLine();
if (Input.Contains("Create new list:"))
{
foreach (char character in Input)
{
if (character == ',')//when it reach a comma
{
//code goes here, where I got stuck...
}
}
}
Edit: I didn`t know the existence of "Split" my mistake... but at least it would great if you could explain me to to use it for the problem above?
You can use this:
String words = "word1, word2, word3";
List:
List<string> wordsList= words.Split(',').ToList<string>();
Array:
string[] namesArray = words.Split(',');
#patrick Artner beat me to it, but you can just split the input with the comma as the argument, or whatever you want the argument to be.
This is the example, and you will learn from the documentation.
using System;
public class Example {
public static void Main() {
String value = "This is a short string.";
Char delimiter = 's';
String[] substrings = value.Split(delimiter);
foreach (var substring in substrings)
Console.WriteLine(substring);
}
}
The example displays the following output:
Thi
i
a
hort
tring.

Move part of string to another string

Maybe I don't have the right keywords but I can't seem to find how to do it.
Let's say I have these two string :
firstString = "I am a string";
secondString = "I am a long";
Is there a method that would allow me to move part of string 1 to string 2 ?
Move, not copy.
The final results would be :
firstString = "I am a"
secondString = "I am a long string"
The Problem
I have a string that contains a lot of characters. I want to send this string to SQLServer but the function that receives it can't hold more than 8000 char. So I need to send a request every 8000 characters.
Check if String1 is longer than 8000 Char
If it is, take the first 8000 Char and MOVE them into String2
Insert String2 into SQL
Repeat
If it's lenght is smaller than 8000 Char, send String 1 to SQL
Strings are immutable so what you are really doing is reassigning part of firstString to itself and assigning the other part concatenated to the end of secondString. There is no built in method to achieve this, but the code is pretty simple
secondString += firstString.Substring(6);
firstString = firstString.Substring(0,6);
Is there a method that would allow me to move part of string 1 to string 2 ? Move, not copy.
Since .NET strings are immutable, they cannot support methods with "move" semantic. Every modification of a string requires creation of a new object, entailing copying.
EDIT (in response to the edit of the question) It looks like your problem has to do with splitting the string at 8K characters, not necessarily moving parts of the string. In this case, you could use this simple code to pass parts of the string to SQL:
string string1 = GetReallyLongString();
const int sqlMax = 8000;
while (true) {
if (string1.Length > sqlMax) {
SendToSql(string1.Substring(0, sqlMax));
string1 = string1.Substring(sqlMax);
} else {
SendToSql(string1);
break;
}
}
Here is a quick demo on ideone.
As strings are immutable, you can't change them. You create new strings with parts from the original strings:
firstString = "I am a string";
secondString = "I am a long";
// concatenate second string with part from first string
secondSring = secondString + firstString.Substring(6);
// create a new string from part of the first string
firstString = firstString.Substring(0, 6);
Many ways to do that:
var partofstring = firstString.Substring(10, 14);
firstString = firstString.Replace(partofstring, "");
secondString += partofstring;
Inspired by dasblinkenlight's solution, but using yield to make a static method, and using as few substrings as possible to reduce memory usage.
using System;
using System.Collections.Generic;
public class Test
{
public static void Main()
{
string string1 = "quick brown fox jumps over the lazy dog";
foreach (var strSection in string1.SplitInto(8))
Console.WriteLine("'{0}'", strSection);
}
}
public static class MyExtensions
{
public static IEnumerable<string> SplitInto(this string value, int size)
{
for (int i = 0; i < value.Length; i += size)
{
if (i + size <= value.Length)
yield return value.Substring(i, size);
else
yield return value.Substring(i);
}
}
}
See it run at Ideone.

Split a filename in 2 groups

I am making an application which "Filewatches" a folder and when a file is created in there it will automatically be mailed to the customer.
The problem is that i haven't found any information on how to split filenames
For example i have a file called : "Q1040500005.xls"
I need the first 5 characters seperated from the last 5, so basically split it in half (without the extension ofcourse)
And my application has to recognize the "Q1040" and the "500005" as seperate strings.
Which will be recognized in the database which contains The query number (Q1040) and the customer number "500005" the email of the customer and the subject of the queryfile.
How can i do this the easiest way?
Thanks for the help!
Use SubString method http://msdn.microsoft.com/es-es/library/aka44szs(v=vs.80).aspx
int lengthFilename = filename.Length - 4; //substract the string ".xls";
int middleLength = lengthFilename/2;
String filenameA = filename.SubString(0, middleLength);
String filenameB = filename.SubString(middleLength, lengthFilename - middleLength);
Is string.Substring method what you're looking for?
Use String.SubString(int startindex, int length)
String filename = Q1040500005.xls
var queryNumber = filename.Substring(0, 5); //Q1040
var customerNumber = filename.Substring(5, 6); //500005
This assumes your strings are a constant length.
Hope this helps.
You can use string.SubString() here
string a = fileName.SubString(0, 5); // "Q1040"
string b = fileName.SubString(5, 5); // "50000" <- Are you sure you didn't mean "last 6"?
string b2 = fileName.SubString(5, 6); // "500005"
This only works, if both strings have a constant fixed length
Edit:
If on the other hand, both strings can have variable length, I'd recommend you use a separator to divide them ("Q1040-500005.xml"), then use string.Split()
string[] separatedStrings = fileName.Split(new char[] { '-', '.' });
string a = separated[0]; // "Q1040"
string b = separated[1]; // "500005"
string extension = separated[2]; // "xls"

How to split a string with '#' in C#

I tried to split a string wich contains these character #
domicilioSeparado = domicilio.Split(#"#".ToCharArray());
but every time the array contains just one member. I've tried a lot of combinations but anything seems to work, I also tried to replace the string with a blank space and it kinda works - the problem is that it remains a single string.
domicilio = domicilio.Replace(#"#", #" ");
How can I resolve this?
Complete code:
String[] domicilioSeparado;
String domicilio = dbRow["DOMICILIO"].ToString();
domicilioSeparado = domicilio.Split(#"#".ToCharArray());
if (Regex.IsMatch(domicilioSeparado.Last(), #"\d"))
{
String domicilioSinNum = "";
domicilioSinNum = domicilioSeparado[0];
custTable.Rows.Add(counter, dbRow["CUENTA"], nombre,
paterno, materno, domicilioSinNum, domicilioSeparado.Last(), tipoEntidad);
}
If you just want to split a string on a delimiter, in this instance '#', then you can use this:
domicilioSeparado = domicilio.Split("#");
That should give you what you want. Your second attempt simply replaces all the characters '#' in the string with ' ', which doesn't seem to be what you want. Can we see the string you're trying to split? That might help explain why it's not working.
EDIT:
Ok, here's how I think your code should look, give this a shot and let me know how it goes.
List<string> domicilioSeparado = new List<string>();
String domicilio = dbRow["DOMICILIO"].ToString();
domicilioSeparado = domicilio.Split("#");
if (Regex.IsMatch(domicilioSeparado.Last(), #"\d"))
{
String domicilioSinNum = "";
domicilioSinNum = domicilioSeparado[0];
custTable.Rows.Add(counter, dbRow["CUENTA"], nombre,
paterno, materno, domicilioSinNum, domicilioSeparado.Last(), tipoEntidad);
}
Try this:
string[] domicilioSeparado;
domicilioSeparado = domicilio.Split('#');
Some notes:
1 - It is ('#'), instead of ("#"); 2 - Replace does not split a string, it only replace that part, keeping as a single string.
In case you want an example that includes the printing of the whole array:
string domicilio = "abc#def#ghi";
string[] domicilioSeparado;
domicilioSeparado = domicilio.Split('#');
for (int i = 0; i < domicilioSeparado.Length; i++)
{
MessageBox.Show(domicilioSeparado[i]);
}
It will open a Message Box for each element within domicilioSeparado.

Categories