Take the first characters [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have this String: Hello to all. I want to take first 2 charcters from each word. The result: Hetoal. How can I do? I tried with a foreach
foreach( string str in String)
but I received an error: Cannot convert type char to String

You will need to split the sentence string into words, like this:
var sentence = "Hello to all.";
var words = sentence.Split(' ');
Then you can loop through each of the words in the sentence and grab the first two characters of each and append them to a result, like this:
string result;
var resultBuilder = new StringBuilder();
foreach(string word in words)
{
// Get the first two characters if word has two characters
if (word.Length >= 2)
{
resultBuilder.Append(word.Substring(0, 2));
}
else
{
// Append the whole word, because there are not two first characters to get
resultBuilder.Append(word);
}
}
result = resultBuilder.ToString();

Code example :
string someString = "Hello to all";
string[] words = someString.Split(' ');
string finalString = "";
foreach (string word in words) {
finalString += word.Substring(0, 2);
}
// finalString = "Hetoal";
This splits the string into words and then foreach word it finds the first 2 characters and appends them to the finalString object.

One possible solution can be
string str = "Hello to all.";
StringBuilder output = new StringBuilder();
foreach (string s in str.Split(' '))
{
output.Append(s.Take(2));
}
string result = output.ToString();

string myString = "Hello to all";
var result = myString
.Split(' ')
.Select(x => x.Substring(0,Math.Min(x.Length,2)))
.Aggregate((y,z) => y + z);

You can do this
split your string around space
string[] words = s.Split(' ');
foreach (string word in words)
{
Console.WriteLine(word.Substring(0,2));
}

Some linq here:
string s = "Hello to all";
var words = s.Split(' ');
var result = new string(words.SelectMany(w=>w.Take(2)).ToArray());

String str = "Hello to all";
String[] words = str.Split(' ');
String completeWord = "";
foreach (String word in words)
{
if(word.Length>1)
completeWord+=word.Substring(0, 2);
}

//original message
string message = "hello to all";
//split into a string array using the space
var messageParts = message.Split(' ');
//The SelectMany here will select the first 2 characters of each
// array item. The String.Join will then concat them with an empty string ""
var result = String.Join("",messageParts.SelectMany(f=>f.Take(2)));

string word = "Hellow to all";
string result = "";
foreach(var item in word.Take(2))
{
result += item;
}

string str = "Hello to all";
string result = str.Split().Select(word => word.Substring(0, 2)).Aggregate((aggr, next) => aggr + next);

Related

find and extract a number from a string C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a requirement to find and extract a number contained within a string.
For example, from these strings:
"O:2275000 BF:3060000 D:3260000 E:3472000 I:3918000 T:4247000 UF:4777000 A:4904000 AD:5010000 X:5243000 G:21280000"
extract :
1.2275000
2.3060000
3.3260000
....
It would be :
string temp = yourText;
List<int> numbers = new List<int>();
Regex re = new Regex(#"\d+");
Match m = re.Match(temp);
while (m.Success)
{
numbers.Add(Convert.ToInt32(m.Value));
temp = temp.Substring(m.Index + m.Length);
m = re.Match(temp);
}
First of all, you mentioned "from these strings", though you gave a single string. I am not clear about this part.
Secondly, what do you mean by extract? Do you want to find the position of a number in the string? If yes then you can simply use string search as following
string str = "O:2275000 BF:3060000 D:3260000";
int index = str.IndexOf("3060000");
if (index != -1)
{
Console.WriteLine(index);
}
else
{
Console.WriteLine("Not Found");
}
Or if the problem is stated like that: you were given a string and you want to extract the numbers out of it, then you can do it like so:
List<decimal> findNumbers(string str)
{
List<decimal> x = new List<decimal>();
string tokens = "";
foreach (char ch in str)
{
if (Char.IsNumber(ch))
{
tokens = tokens + ch;
}
if (!Char.IsNumber(ch) && !String.IsNullOrEmpty(tokens))
{
decimal num = Convert.ToDecimal(tokens);
x.Add(Convert.ToDecimal(num));
tokens = "";
}
}
if (String.IsNullOrEmpty(tokens))
{
x.Add(Convert.ToDecimal(tokens));
}
return x;
}
this function returns the list of numbers available in the string.
We can try using string split here:
string input = "O:2275000 BF:3060000 D:3260000";
string[] parts = input.Split(' ');
string[] numbers = parts
.Select(s => s.Split(':')[1])
.ToArray();
foreach (string n in numbers)
{
Console.WriteLine(n);
}
This prints:
2275000
3060000
3260000
You can do this in a single line with Linq.
string numbers = "O:2275000 BF:3060000 D:3260000 E:3472000 I:3918000 T:4247000 UF:4777000 A:4904000 AD:5010000 X:5243000 G:21280000";
List<int> list = numbers.Split(' ').Select(x => Convert.ToInt32(string.Concat(x.Where(Char.IsDigit)))).ToList();
Tim Biegeleisen's answer is correct except it does not produce floating point output as you mentioned in your question. In his answere, just replace foreach loop with for statement, like this:
string input = "O:2275000 BF:3060000 D:3260000";
string[] parts = input.Split(' ');
string[] numbers = parts
.Select(s => s.Split(':')[1])
.ToArray();
for(int i = 0; i < numbers.Length; i++)
{
Console.WriteLine("{0}.{1}", i+1, numbers[i]);
}

Is there a simple way to apply grammatical casing to a string?

I am developing a Xamarin.Forms application on UWP
I have an Editor control - Basically a multi-line TextBox
I am trying to apply some simple grammatical casing to the string basically the following:
Capitalise the word "I"
Capitalise the First word
Capitalise the First word after a full stop.
I have managed to do the first two, and am a bit stuck on the third and was wondering if there is an easier way or whether my algorithm can be adapted.
What I have so far is:
public static string ToGramaticalCase(this string s)
{
var thingsToCapitalise = new String[] {"i"};
string newString = string.Empty;
if (!string.IsNullOrEmpty(s))
{
var wordSplit = s.Split(' ');
if (wordSplit.Count() > 1)
{
var wordToCapitalise = wordSplit.First();
wordToCapitalise = wordToCapitalise.Substring(0, 1).ToUpper() + wordToCapitalise.Substring(1);
var value = wordToCapitalise + s.Substring(wordToCapitalise.Length);
foreach (var item in thingsToCapitalise)
{
value = value.Replace(string.Format(" {0} ", item), string.Format(" {0} ", item.ToUpper()));
}
newString = value;
}
}
return newString;
}
This method will capitalize all words after ". ":
[Test]
public void Test()
{
var result = NewSentenceWithUpperLetter("Sentence one. sentence two.");
// result will be 'Sentence one. Sentence two.'
}
private string NewSentenceWithUpperLetter(string text)
{
var splitted = text.Split(' ');
for (var i = 1; i < splitted.Length; i++)
{
if (splitted[i - 1].EndsWith("."))
{
splitted[i] = splitted[i][0].ToString().ToUpper() + splitted[i].Substring(1);
}
}
return string.Join(" ", splitted);
}
Just split the string also on full stop. Change this line:
var wordSplit = s.Split(' ');
Into this:
var wordSplit = s.Split(new char[] { ' ', '.' },StringSplitOptions.RemoveEmptyEntries);
Edit
This extension method would do what you want:
public static string ToTitleCase(this string input)
{
string output =
String.Join(" ", input.Split(new char[] { ' ' },StringSplitOptions.RemoveEmptyEntries)
.ToList()
.Select(x => x = x.Length>1?
x.First().ToString().ToUpper() + x.Substring(1):
x.First().ToString().ToUpper()));
output =
String.Join(".", output.Split(new char[] { '.' },StringSplitOptions.RemoveEmptyEntries)
.ToList()
.Select(x => x = x.Length > 1 ?
x.First().ToString().ToUpper() + x.Substring(1) :
x.First().ToString().ToUpper()));
return output;
}
Test string: string input = "i try this test sentence .now it works as i want";
Output: I Try This Test Sentence .Now It Works As I Want

Parsing a string with, seemingly, no delimiter

I have the following string that I need to parse out so I can insert them into a DB. The delimiter is "`":
`020 Some Description `060 A Different Description `100 And Yet Another `
I split the string into an array using this
var responseArray = response.Split('`');
So then each item in the responseArrray[] looks like this: 020 Some Description
How would I get the two different parts out of that array? The 1st part will be either 3 or 4 characters long. 2nd part will be no more then 35 characters long.
Due to some ridiculous strangeness beyond my control there is random amounts of space between the 1st and 2nd part.
Or put the other two answers together, and get something that's more complete:
string[] response = input.Split(`);
foreach (String str in response) {
int splitIndex = str.IndexOf(' ');
string num = str.Substring(0, splitIndex);
string desc = str.Substring(splitIndex);
desc.Trim();
}
so, basically you use the first space as a delimiter to create 2 strings. Then you trim the second one, since trim only applies to leading and trailing spaces, not everything in between.
Edit: this a straight implementation of Brad M's comment.
You can try this solution:
var inputString = "`020 Some Description `060 A Different Description `100 And Yet Another `";
int firstWordLength = 3;
int secondWordMaxLength = 35;
var result =inputString.Split('`')
.SelectMany(x => new[]
{
new String(x.Take(firstWordLength).ToArray()).Trim(),
new String(x.Skip(firstWordLength).Take(secondWordMaxLength).ToArray()).Trim()
});
Here is the result in LINQPad:
Update: My first solution has some problems because the use of Trim after Take.Here is another approach with an extension method:
public static class Extensions
{
public static IEnumerable<string> GetWords(this string source,int firstWordLengt,int secondWordLenght)
{
List<string> words = new List<string>();
foreach (var word in source.Split(new[] {'`'}, StringSplitOptions.RemoveEmptyEntries))
{
var parts = word.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
words.Add(new string(parts[0].Take(firstWordLengt).ToArray()));
words.Add(new string(string.Join(" ",parts.Skip(1)).Take(secondWordLenght).ToArray()));
}
return words;
}
}
And here is the test result:
Try this
string response = "020 Some Description060 A Different Description 100 And Yet Another";
var responseArray = response.Split('`');
string[] splitArray = {};
string result = "";
foreach (string it in responseArray)
{
splitArray = it.Split(' ');
foreach (string ot in splitArray)
{
if (!string.IsNullOrWhiteSpace(ot))
result += "-" + ot.Trim();
}
}
splitArray = result.Substring(1).Split('-');
string[] entries = input.Split('`');
foreach (string s in entries)
GetStringParts(s);
IEnumerable<String> GetStringParts(String input)
{
foreach (string s in input.Split(' ')
yield return s.Trim();
}
Trim only removes leading/trailing whitespace per MSDN, so spaces in the description won't hurt you.
If the first part is an integer
And you need to account for some empty
For me the first pass was empty
public void parse()
{
string s = #"`020 Some Description `060 A Different Description `100 And Yet Another `";
Int32 first;
String second;
if (s.Contains('`'))
{
foreach (string firstSecond in s.Split('`'))
{
System.Diagnostics.Debug.WriteLine(firstSecond);
if (!string.IsNullOrEmpty(firstSecond))
{
firstSecond.TrimStart();
Int32 firstSpace = firstSecond.IndexOf(' ');
if (firstSpace > 0)
{
System.Diagnostics.Debug.WriteLine("'" + firstSecond.Substring(0, firstSpace) + "'");
if (Int32.TryParse(firstSecond.Substring(0, firstSpace), out first))
{
System.Diagnostics.Debug.WriteLine("'" + firstSecond.Substring(firstSpace-1) + "'");
second = firstSecond.Substring(firstSpace).Trim();
}
}
}
}
}
}
You can get the first part by finding the first space and make a substring. The second is also a Substring. Try something like this.
foreach(string st in response)
{
int index = response.IndexOf(' ');
string firstPart = response.Substring(0, index);
//string secondPart = response.Substring(response.Lenght-35);
//better use this
string secondPart = response.Substring(index);
secondPart.Trim();
}

Split string into string array of single characters

I want to something as simple as turning "this is a test" into
new string[] {"t","h","i","s"," ","i","s"," ","a"," ","t","e","s","t"}
Would I really have to do something like
test = "this is a test".Select(x => x.ToString()).ToArray();
edit: To clarify, I don't want a char array, ideally I want an array of string. I don't really see anything wrong with the above code except for the fact that I would think there is an easier way.
I believe this is what you're looking for:
char[] characters = "this is a test".ToCharArray();
Strings in C# already have a char indexer
string test = "this is a test";
Console.WriteLine(test[0]);
And...
if(test[0] == 't')
Console.WriteLine("The first letter is 't'");
This works too...
Console.WriteLine("this is a test"[0]);
And this...
foreach (char c in "this is a test")
Console.WriteLine(c);
EDIT:
I noticed the question was updated with regards to char[] arrays. If you must have a string[] array, here's how you split a string at each character in c#:
string[] test = Regex.Split("this is a test", string.Empty);
foreach (string s in test)
{
Console.WriteLine(s);
}
Simple!!
one line:
var res = test.Select(x => new string(x, 1)).ToArray();
Try this:
var charArray = "this is a test".ToCharArray().Select(c=>c.ToString());
You can just use String.ToCharArray() and then treat each char as a string in your code.
Here's an example:
foreach (char c in s.ToCharArray())
Debug.Log("one character ... " +c);
Most likely you're looking for the ToCharArray() method. However, you will need to do slightly more work if a string[] is required, as you noted in your post.
string str = "this is a test.";
char[] charArray = str.ToCharArray();
string[] strArray = str.Select(x => x.ToString()).ToArray();
Edit: If you're worried about the conciseness of the conversion, I suggest you make it into an extension method.
public static class StringExtensions
{
public static string[] ToStringArray(this string s)
{
if (string.IsNullOrEmpty(s))
return null;
return s.Select(x => x.ToString()).ToArray();
}
}
Convert the message to a character array, then use a for loop to change it to a string
string message = "This Is A Test";
string[] result = new string[message.Length];
char[] temp = new char[message.Length];
temp = message.ToCharArray();
for (int i = 0; i < message.Length - 1; i++)
{
result[i] = Convert.ToString(temp[i]);
}
string input = "this is a test";
string[] afterSplit = input.Split();
foreach (var word in afterSplit)
Console.WriteLine(word);
Result:
this
is
a
test

How to split string that delimiters remain in the end of result?

I have several delimiters. For example {del1, del2, del3 }.
Suppose I have text : Text1 del1 text2 del2 text3 del3
I want to split string in such way:
Text1 del1
text2 del2
text3 del3
I need to get array of strings, when every element of array is texti deli.
How can I do this in C# ?
String.Split allows multiple split-delimeters. I don't know if that fits your question though.
Example :
String text = "Test;Test1:Test2#Test3";
var split = text.Split(';', ':', '#');
//split contains an array of "Test", "Test1", "Test2", "Test3"
Edit: you can use a regex to keep the delimeters.
String text = "Test;Test1:Test2#Test3";
var split = Regex.Split(text, #"(?<=[;:#])");
// contains "Test;", "Test1:", "Test2#","Test3"
This should do the trick:
const string input = "text1-text2;text3-text4-text5;text6--";
const string matcher= "(-|;)";
string[] substrings = Regex.Split(input, matcher);
StringBuilder builder = new StringBuilder();
foreach (string entry in substrings)
{
builder.Append(entry);
}
Console.Out.WriteLine(builder.ToString());
note that you will receive empty strings in your substring array for the matches for the two '-';s at the end, you can choose to ignore or do what you like with those values.
You could use a regex. For a string like this "text1;text2|text3^" you could use this:
(.*;|.*\||.*\^)
Just add more alternative pattens for each delimiter.
If you want to keep the delimiter when splitting the string you can use the following:
string[] delimiters = { "del1", "del2", "del3" };
string input = "text1del1text2del2text3del3";
string[] parts = input.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
for(int index = 0; index < parts.Length; index++)
{
string part = parts[index];
string temp = input.Substring(input.IndexOf(part) + part.Length);
foreach (string delimter in delimiters)
{
if ( temp.IndexOf(delimter) == 0)
{
parts[index] += delimter;
break;
}
}
}
parts will then be:
[0] "text1del1"
[1] "text2del2"
[2] "text3del3"
As #Matt Burland suggested, use Regex
List<string> values = new List<string>();
string s = "abc123;def456-hijk,";
Regex r = new Regex(#"(.*;|.*-|.*,)");
foreach(Match m in r.Matches(s))
values.Add(m.Value);

Categories

Resources