Enter the first character of the word

Enter the first character of the word

  • Текст
  • Веб-страница

Enter the first character of the word «Panda» (Note: anything but a valid answer)

0/5000

Результаты (русский) 1: [копия]

Скопировано!

Введите первый символ слова «Панда» (Примечание: ничего, кроме действительный ответ)

переводится, пожалуйста, подождите..

Результаты (русский) 2:[копия]

Скопировано!

Ввести первую букву слова «Panda» (Примечание: ничего, кроме действительного ответа)

переводится, пожалуйста, подождите..

Результаты (русский) 3:[копия]

Скопировано!

Введите первую букву слова «Панда» (Примечание: не правильный ответ)

переводится, пожалуйста, подождите..

Другие языки

  • English
  • Français
  • Deutsch
  • 中文(简体)
  • 中文(繁体)
  • 日本語
  • 한국어
  • Español
  • Português
  • Русский
  • Italiano
  • Nederlands
  • Ελληνικά
  • العربية
  • Polski
  • Català
  • ภาษาไทย
  • Svenska
  • Dansk
  • Suomi
  • Indonesia
  • Tiếng Việt
  • Melayu
  • Norsk
  • Čeština
  • فارسی

Поддержка инструмент перевода: Клингонский (pIqaD), Определить язык, азербайджанский, албанский, амхарский, английский, арабский, армянский, африкаанс, баскский, белорусский, бенгальский, бирманский, болгарский, боснийский, валлийский, венгерский, вьетнамский, гавайский, галисийский, греческий, грузинский, гуджарати, датский, зулу, иврит, игбо, идиш, индонезийский, ирландский, исландский, испанский, итальянский, йоруба, казахский, каннада, каталанский, киргизский, китайский, китайский традиционный, корейский, корсиканский, креольский (Гаити), курманджи, кхмерский, кхоса, лаосский, латинский, латышский, литовский, люксембургский, македонский, малагасийский, малайский, малаялам, мальтийский, маори, маратхи, монгольский, немецкий, непальский, нидерландский, норвежский, ория, панджаби, персидский, польский, португальский, пушту, руанда, румынский, русский, самоанский, себуанский, сербский, сесото, сингальский, синдхи, словацкий, словенский, сомалийский, суахили, суданский, таджикский, тайский, тамильский, татарский, телугу, турецкий, туркменский, узбекский, уйгурский, украинский, урду, филиппинский, финский, французский, фризский, хауса, хинди, хмонг, хорватский, чева, чешский, шведский, шона, шотландский (гэльский), эсперанто, эстонский, яванский, японский, Язык перевода.

  • От тебя
  • неделя
  • Может тебе такой вариант ответа не нрави
  • ядерная война
  • What was the name of your best friend as
  • я доктор
  • Заехай за мной на Кирова 46. А потом реш
  • Я постараюсь на этих выходных
  • didi madloba
  • it means
  • Сколько времени Вы работаете в этом мест
  • а сколько вам лет?
  • introduce
  • справа от их дома находится больница
  • Я не пью спиртное
  • الحقيقة ليست سوى وهم، لكنه وهم ثابت
  • Must agree and reach an understanding
  • こんにちは。私はロシア人です。
  • А я не всегда понимаю
  • Группа
  • Еще я пишу стихи. Я стану известным поэт
  •  Montieren Sie den Antrieb fachgerecht
  • Большое спасибо за оперативность и нерав
  • It may get close tondisapearing

explode() on the spaces, then you use an appropriate substring method to access the first character of each word.

$words = explode(" ", "Community College District");
$acronym = "";

foreach ($words as $w) {
  $acronym .= mb_substr($w, 0, 1);
}

If you have an expectation that multiple spaces may separate words, switch instead to preg_split()

$words = preg_split("/s+/", "Community College District");

Or if characters other than whitespace delimit words (-,_) for example, use preg_split() as well:

// Delimit by multiple spaces, hyphen, underscore, comma
$words = preg_split("/[s,_-]+/", "Community College District");

answered Mar 14, 2012 at 16:58

Michael Berkowski's user avatar

Michael BerkowskiMichael Berkowski

266k46 gold badges443 silver badges388 bronze badges

2

The best way to accomplish this is with regular expressions.

Lets break down what you want in a logical way: You want every character from the string is at the beginning of a word. The best way to identify those characters is to look for those characters that are preceded by white space.

So we start with a lookbehind for that space character, followed by any character:

/(?<=s)./

This will find any character preceded by a space. But — the first character in the string is a character in the string is one you want extract. And because it’s the first character in the string, it can’t be preceded by a space. So we want to match anything preceded by a space or the first character in the string, so we add a start-of-subject assertion:

/(?<=s|^)./

Now we are getting closer. But what if the string contains blocks of multiple spaces? What if it contains a space followed by a punctuation character? We probably don’t want to match any of those, in fat we probably just want to match letters. We can do that with «any word character» w escape sequence. And we can make are expression case-insensitive using the i modifier as well as u modifier to support utf-8 characters.

So we end up with:

/(?<=s|^)w/iu

But how do we actually use this in PHP? Well we want to match all occurrences of the regular expression within the string so we use (you guessed it) preg_match_all():

$string = "Progress in Veterinary Science";

$expr = '/(?<=s|^)w/iu';
preg_match_all($expr, $string, $matches);

Now we have all the characters we wanted to extract. To construct the result string you show, we need to join them together again:

$result = implode('', $matches[0]);

…and we need to ensure that they are all upper-case:

$result = mb_strtoupper($result);

And that’s really all there is to it.

See it working


Here’s a slightly compressed version, using the alternative regex from Leigh’s comment to «capture the initial letters of words separated by hyphens, full stops, etc.» (rather than only spaces.)

$str="Foo Bar";
preg_match_all('/(?<=b)w/iu',$str,$matches);
$result=mb_strtoupper(implode('',$matches[0]));

5

Assuming the words are all split by spaces, this is a suitable solution:

$string = "Progress in Veterinary Science";

function initials($str) {
    $ret = '';
    foreach (explode(' ', $str) as $word)
        $ret .= strtoupper($word[0]);
    return $ret;
}

echo initials($string); // would output "PIVS"

answered Apr 23, 2013 at 8:34

casraf's user avatar

casrafcasraf

20.7k8 gold badges55 silver badges91 bronze badges

5

There are a lot of explode answers. I think using the strtok function is a much more elegant and memory-efficient solution:

function createAcronym($string) {
    $output = null;
    $token  = strtok($string, ' ');
    while ($token !== false) {
        $output .= $token[0];
        $token = strtok(' ');
    }
    return $output;
}
$string = 'Progress in Veterinary Science';
echo createAcronym($string, false);

Here is a more robust and useful function, which supports UTF8 characters and the option to only use the capitalized words:

function createAcronym($string, $onlyCapitals = false) {
    $output = null;
    $token  = strtok($string, ' ');
    while ($token !== false) {
        $character = mb_substr($token, 0, 1);
        if ($onlyCapitals and mb_strtoupper($character) !== $character) {
            $token = strtok(' ');
            continue;
        }
        $output .= $character;
        $token = strtok(' ');
    }
    return $output;
}
$string = 'Leiðari í Kliniskum Útbúgvingum';
echo createAcronym($string);

answered Apr 23, 2013 at 8:49

Sverri M. Olsen's user avatar

Sverri M. OlsenSverri M. Olsen

13k3 gold badges36 silver badges52 bronze badges

6

As explained by others, classical way consist in iterating over each word of your initial string, reduce the word to its first letter, and combine those first letters together.

Here is a helper method combining the different steps.

/**
 * @return string
 */
function getInitials($string = null) {
    return array_reduce(
        explode(' ', $string),
        function ($initials, $word) {
            return sprintf('%s%s', $initials, substr($word, 0, 1));
        },
        ''
    );
}

NB : this will return an empty string in case the given string is empty.

getInitials('Community College District')

string ‘CCD’ (length=3)

getInitials()

string » (length=0)

getInitials('Lorem ipsum dolor sic amet')

string ‘Lidsa’ (length=5)

Of course you can add filters to the callback function of array_reduce(), such as strtoupper() if you prefer only uppercased initials for instance.

answered Mar 26, 2017 at 11:53

Flo Schild's user avatar

Flo SchildFlo Schild

4,9744 gold badges39 silver badges55 bronze badges

Michael Berkowski‘s (and others) answer, simplified to one line and working correctly on multi-byte characters (i.e. making abbreviation / initials out of non-Latin string):

foreach(explode(' ', $words) as $word) $acronym .= mb_substr($word, 0, 1, 'utf-8');

Using mb_substr($word, 0, 1, 'utf-8'), instead of $word[0] seems to be must, if you’re working on non-Latin, multi-byte strings and characters, i.e. when using UTF-8 encoded strings.

answered Aug 25, 2014 at 9:16

trejder's user avatar

trejdertrejder

17k27 gold badges123 silver badges215 bronze badges

0

$temp = explode(' ', $string);
$result = '';
foreach($temp as $t)
    $result .= $t[0];

answered Mar 14, 2012 at 16:58

Ascherer's user avatar

AschererAscherer

8,1933 gold badges42 silver badges60 bronze badges

Like this

preg_match_all('#(?<=s|b)pL#u', $String, $Result);
echo '<pre>' . print_r($Result, 1) . '</pre>';

answered Apr 23, 2013 at 8:45

Winston's user avatar

WinstonWinston

1,7482 gold badges17 silver badges29 bronze badges

6

$str = 'I am a String!';
echo implode('', array_map(function($v) { return $v[0]; }, explode(' ', $str)));

// would output IaaS

answered May 28, 2013 at 11:38

billyonecan's user avatar

billyonecanbillyonecan

20k8 gold badges42 silver badges64 bronze badges

Something I’ve cooked up.

/**
 * Return the first letter of each word in uppercase - if it's too long.
 *
 * @param string $str
 * @param int $max
 * @param string $acronym
 * @return string
 */
function str_acronym($str, $max = 12, $acronym = '')
{
    if (strlen($str) <= $max) return $str;

    $words = explode(' ', $str);

    foreach ($words as $word)
    {
        $acronym .= strtoupper(substr($word, 0, 1));
    }

    return $acronym;
}

answered Oct 12, 2015 at 11:41

function acronym( $string = '' ) {
    $words = explode(' ', $string);
    if ( ! $words ) {
        return false;
    }
    $result = '';
    foreach ( $words as $word ) $result .= $word[0];
    return strtoupper( $result );
}

answered Mar 14, 2012 at 17:06

smassey's user avatar

smasseysmassey

5,81523 silver badges37 bronze badges

Why not using the str_word_count function for this?

  1. get each word as a row in an array
  2. reduce that array to the first letter

    $acronym = array_reduce(
    str_word_count(«Community College District», 1),
    function($res , $w){
    return $res . $w[0];
    }
    );

answered Mar 1, 2019 at 13:39

Spir's user avatar

SpirSpir

1,7071 gold badge16 silver badges27 bronze badges

Assuming that the original string is properly built (trimmed and without double spaces), this is what I do:

$name = 'John Doe';
$initials = implode( '', array_map( function ( $part ) { 
    return strtoupper( $part['0'] );
}, explode( ' ', $name ) ) );

Basically, breaking the string into words, extracting & capitalizing the first character of a word, and gluing them back together.

answered Feb 2, 2021 at 15:55

Hike Nalbandyan's user avatar

Hike NalbandyanHike Nalbandyan

9441 gold badge10 silver badges28 bronze badges

I think you have to explode and join them back again …..

<?php
$string  = "Progress in Veterinary Science";
$pieces = explode(" ", $string);
$str="";
foreach($pieces as $piece)
{
    $str.=$piece[0];
}    
echo $str; /// it will result into  "PiVS"
?>

answered Apr 23, 2013 at 8:37

Ravindra Shekhawat's user avatar

Using Prateeks foundation, here’s a simple example with explanations

//  initialize variables
$string = 'Capitalize Each First Word In A String';
$myCapitalizedString = '';

//  here's the code
$strs=explode(" ",$string);    
foreach($strs as $str) {
  $myCapitalizedString .= $str[0]; 
}

//  output
echo $myCapitalizedString;  // prints 'CEFWIAS'

answered Jun 2, 2013 at 8:29

Rob Stocki's user avatar

Rob StockiRob Stocki

1461 silver badge9 bronze badges

0

If there are more number of spaces between two letters in the input string then try this.

function first_letter($str)
{
    $arr2 = array_filter(array_map('trim',explode(' ', $str)));
    $result='';
    foreach($arr2 as $v)
    {
        $result.=$v[0];
    }
    return $result;
}

$str="    Let's   try   with    more   spaces       for  fun .   ";

echo first_letter($str);

Demo1

Alternative of same code

function first_letter($str)
{
    return implode('', array_map(function($v) { return $v[0]; },array_filter(array_map('trim',explode(' ', $str)))));;
}

$str="    Let's   try   with    more   spaces       for  fun .   ";

echo first_letter($str);

Demo2

answered Feb 26, 2016 at 12:43

Durgesh Tiwari's user avatar

Here’s a function that gets you the initials of a name and if the initials are only 1 letter then it returns the first 2 letters of the first name.

function getNameInitials($name) {

    preg_match_all('#(?<=s|b)pL#u', $name, $res);
    $initials = implode('', $res[0]);

    if (strlen($initials) < 2) {
        $initials = strtoupper(substr($name, 0, 2));
    }

    return strtoupper($initials);
}

answered May 9, 2018 at 14:55

Salam's user avatar

SalamSalam

1,03214 silver badges19 bronze badges

1

Try this-

$strs=explode(" ",$string);

foreach($strs as $str)
  echo $str[0];

answered Apr 23, 2013 at 8:34

Prateek Shukla's user avatar

Prateek ShuklaPrateek Shukla

5932 gold badges7 silver badges27 bronze badges

Something like this should do the trick :

$string = 'Some words in a string';
$words = explode(' ', $string); // array of word
foreach($words as $word){
    echo $word[0]; // first letter
}

answered Apr 23, 2013 at 8:37

Marshall's user avatar

MarshallMarshall

3291 silver badge7 bronze badges

For the case that you’ll be doing this on large strings (or even directly from file) explode() isn’t the best way to do this. Imagine how much memory will get wasted if you have to split string 2MB large into memory.

With little more coding and (assuming PHP >= 5.0) you can easily implement PHP’s Iterator class that will do exactly this. This will be close to generator in python and long story short, here’s the code:

/**
 * Class for CONTINOUS reading of words from string.
*/
class WordsIterator implements Iterator {
    private $pos = 0;
    private $str = '';
    private $index = 0;
    private $current = null;

    // Regexp explained:
    // ([^\w]*?) - Eat everything non-word before actual word characters
    //              Mostly used only if string beings with non-word char
    // ([\w]+)   - Word
    // ([^\w]+?|$) - Trailing thrash
    private $re = '~([^\w]*?)([\w]+)([^\w]+?|$)~imsS';

    // Primary initialize string
    public function __construct($str) {
        $this->str = $str;
    }

    // Restart indexing
    function rewind() {
        $this->pos = 0;
        $this->index = 0;
        $this->current = null;
    }

    // Fetches current word
    function current() {
        return $this->current;
    }

    // Return id of word you are currently at (you can use offset too)
    function key() {
        return $this->index;
    }

    // Here's where the magic is done
    function next() {
        if( $this->pos < 0){
            return;
        }

        $match = array();
        ++$this->index;

        // If we can't find any another piece that matches... Set pos to -1
        // and stop function
        if( !preg_match( $this->re, $this->str, $match, 0, $this->pos)){
            $this->current = null;
            $this->pos = -1;
            return;
        }

        // Skip what we have read now
        $this->current = $match[2];
        $this->pos += strlen( $match[1]) + strlen( $match[2]) + strlen($match[3]);

        // We're trying to iterate past string
        if( $this->pos >= strlen($this->str)){
            $this->pos = -1;
        }

    }

    // Okay, we're done? :)
    function valid() {
        return ($this->pos > -1);
    }
}

And if you’ll use it on a bit more challenging string:

$a = new WordsIterator("Progress in Veterinary Science. And, make it !more! interesting!nWith new line.");
foreach( $a as $i){
    echo $i;
    echo "n";
}

Will you get the expected result:

Progress
in
Veterinary
Science
And
make
it
more
interesting
With
new
line

So you can easily use $i[0] to fetch first letter.You probably can see that this is more effective solution than splitting whole string into memory (always use only as little memory as possible). You also could easily modify this solution to work with continuous reading of files etc.

answered Apr 23, 2013 at 9:24

Vyktor's user avatar

VyktorVyktor

20.4k6 gold badges62 silver badges96 bronze badges

1

<?php $arr = explode(" ",$String);

foreach($arr as $s)
{
   echo substr($s,0,1);
}

?>

firstly I explode string by spaces then I substr first char.

http://php.net/substr

http://php.net/explode

Vyktor's user avatar

Vyktor

20.4k6 gold badges62 silver badges96 bronze badges

answered Apr 23, 2013 at 8:34

Robert's user avatar

RobertRobert

19.6k5 gold badges57 silver badges84 bronze badges

Try This

function initials($string) {
        if(!(empty($string))) {
            if(strpos($string, " ")) {
                $string = explode(" ", $string);
                $count = count($string);
                $new_string = '';
                for($i = 0; $i < $count; $i++) {
                $first_letter = substr(ucwords($string[$i]), 0, 1);
                $new_string .= $first_letter;
            }
            return $new_string;
            } else {
                $first_letter = substr(ucwords($string), 0, 1);
                $string = $first_letter;
                return $string;
            }
        } else {
            return "empty string!";
        }
    }
    echo initials('Thomas Edison');

answered May 27, 2013 at 4:06

San's user avatar

1

I like Reg Expression over any other method of string extraction, but if you are unfamiliar with Reg Ex then hear is a method using the explode() PHP function:

$string = "David Beckham";
$string_split = explode(" ", $string);
$inititals = $string_split[0][0] . $string_split[1][0];
echo $inititals;

Obviously the above code will only work on a name containing two words.

answered Jan 6, 2016 at 9:38

Matt Jameson's user avatar

This answer https://stackoverflow.com/a/33080232/1046909 but with multibyte strings support:

if (!function_exists('str_acronym')) {
    function str_acronym(string $str, int $min = -1, string $prefix = null): string
    {
        if (mb_strlen($str) <= $min) {
            return $str;
        };

        $words = explode(' ', $str);

        $acronym = strval($prefix);

        foreach ($words as $word) {
            if ($word = trim($word)) {
                $acronym .= mb_strtoupper(mb_substr($word, 0, 1));
            }
        }

        return $acronym;
    }
}

answered Aug 19, 2019 at 15:34

MingalevME's user avatar

MingalevMEMingalevME

1,7071 gold badge20 silver badges18 bronze badges

You can use that function based on the accepted answer from @Michael Berkowski

function buildAcronym($string, $length = 1) {
    $words = explode(" ", $string);
    $acronym = "";
    $length = (self::is_empty($string) || $length <= 0 ? 1 : $length);

    foreach ($words as $i => $w) {
        $i += 1;
        if($i <= $length) {
            $acronym .= $w[0];
        }
    }

    return $acronym;
}

The $length parameter determines how many chars you want to display

USAGE:

$acronym = buildAcronym("Hello World", 2);

answered May 11, 2020 at 20:33

J0rdAn's user avatar

J0rdAnJ0rdAn

1213 silver badges13 bronze badges

I’m a little underwhelmed by the suggested techniques here (despite having so many to choose from).

Assuming your input string is solely composed of whitespace delimited «words» (and you don’t need to validate that the first character of each word is an actual letter), you can use this concise, multibyte safe technique to trim all letters after the first letter from each word and also discard the delimiting whitespaces.

Code: (Demo)

$string = "Let's observe obviously knowledgeable approaches that target helpful items succinctly";

echo preg_replace('~SKS*s*~u', '', $string);

Output:

Lookatthis

If you want to specifically target «letters», you can use p{Ll} and non-letters with P{Ll} (as replacements for S and s. The K restarts the fullstring match — by effect, the matched first matched letter of each word is «set free» before matching more characters to be replaced by the empty string.


I see some other approaches on this page that are using lookbehinds to match the first letter of each word with preg_match_all('~(?<=s|b)pL~u', ...), but notice the effect on fringe cases:

$string = "Let's check some fringe-cases: like @mentions and email@example";
#matches:  ^   ^ ^     ^    ^      ^      ^     ^        ^   ^     ^

I cannot say if these would be desirable results, but if they were, then the pattern could be distilled to ~bpL~u because the word boundary (b) is a zero-length assertion that doesn’t require a lookbehind AND it covers every character that s could match.


I should also mention that any of the answers on this page that are accessing the first character by its offset (using array-like syntax like $word[0]) or substr() will fail whenever a multibyte character is encountered.

answered Apr 1, 2022 at 23:35

mickmackusa's user avatar

mickmackusamickmackusa

42.8k12 gold badges83 silver badges130 bronze badges

Try this

$string  = "Community College District";
echo $result = implode ('',array_map(function ($item) {return strtoupper($item[0]);} , explode(' ', $string)));

answered Jun 23, 2022 at 10:37

MD TAREK HOSSEN's user avatar

1

Introduction:

In this post, I will show you how to get the first character of each word in a string in JavaScript. We will write one program that will take one string as input from the user and prints out the first character of each word in that string as output. If our string is Hello World and Hello Universe, It will return the characters H,W,a,H,U.

This problem can be solved in multiple ways. The easiest way to solve this is by iterating through the characters of the string one by one. Or we can go with ES6 to do that in one line or we can use regex or regular expression.

In this post, I will show you all these three different ways to get the first character of each word in JavaScript.

Method 1: Using a loop:

Using a loop, we can iterate through the characters of a string and get the first character of each word of that string. Below is the complete program:

function getFirstCharacters(str) {
  // 1
  if (str.length == 0) {
    return [];
  }

  // 2
  let result = [];
  let blankFound = false;

  // 3
  if (str[0] != " ") {
    result.push(str[0]);
  }

  // 4
  for (ch of str) {
    if (ch === " ") {
      blankFound = true;
    } else if (blankFound) {
      blankFound = false;
      result.push(ch);
    }
  }

  // 5
  return result;
}

const str1 = "Hello4 World65 123 !!";
const str2 = "123and 456 and 78-1";
const str3 = " Hello World    !!";

console.log(getFirstCharacters(str1));
console.log(getFirstCharacters(str2));
console.log(getFirstCharacters(str3));

Output:

This program will print the below output:

[ 'H', 'W', '1', '!' ]
[ '1', '4', 'a', '7' ]
[ 'H', 'W', '!' ]

Each array holds the first character of words in the string we provided.

Explanation:

The commented numbers in the program denote the step numbers below :

  1. getFirstCharacters function is used to get the first characters of each word in a string. It takes one string as its parameter and returns one array holding the first character of each word in the string. If the provided string is empty, we are returning one empty array
  2. result is an empty array used to hold the first characters. blankFound is a boolean value denotes if any blank character is found. If found, we will add the next character to the array.
  3. In this step, we are checking if the first character of the string is space or not. If not, we are adding it to the array.
  4. This is a for-of loop to iterate through the characters of the string one by one. For each character, we are checking if it is empty or not. If yes, we are assigning blankFound as true. On next iteration, if blankFound is true and if we are getting a non empty character, adding that to the array and reassigning blankFound to false.
  5. Finally, that array result is returned.

Method 2: Using ES6 map and split:

split is used to split one string to words. For example, for the string Hello World !!, if we call split(’ ‘) on this string, it will return one array holding Hello, World and !!.

We can call map to this array of words and get the first character of each word and put them in an array.

Below is the complete program:

function getFirstCharacters(str) {
  let result = [];

  str.split(' ').map(word => word.charAt(0) != '' ? result.push(word.charAt(0)) : '');
  
  return result;
}

const str1 = "Hello4 World65 123 !!";
const str2 = "123and 456 and 78-1";
const str3 = " Hello World    !!";

console.log(getFirstCharacters(str1));
console.log(getFirstCharacters(str2));
console.log(getFirstCharacters(str3));

Output:

It will print :

[ 'H', 'W', '1', '!' ]
[ '1', '4', 'a', '7' ]
[ 'H', 'W', '!' ]

Explanation:

In this example, we are using only one line to solve it. It :

  • splits the string in blank space
  • map all words in the array of words
  • check for each word, if the first character is empty or not. If it is not empty, push the character to the final result array. Else, do nothing.

That’s all.

Method 3: Using regex:

Regex is bit difficult and we need to verify it on different strings to check if it works on all or not. I take this regex pattern from here and you can check with different patterns and different strings.

function getFirstCharacters(str) {
  let result = [];

  return str.match(/(?:s|^)(S)/g).join(',');
  
  return result;
}

const str1 = "Hello4 World65 123 !!";
const str2 = "123and 456 and 78-1";
const str3 = " Hello World    !!";

console.log(getFirstCharacters(str1));
console.log(getFirstCharacters(str2));
console.log(getFirstCharacters(str3));

It will print:

H, W, 1, !
1, 4, a, 7
 H, W, !

You might also like:

  • How to reverse a string in Javascript in one line
  • How to check if a number is perfect or not in Javascript
  • 3 different ways in Javascript to find if a string contains a substring or not
  • Join two or more strings using concat in Javascript
  • JavaScript substr() function explanation with example
  • How to trim a string in JavaScript with examples

C program to find the first occurrence of a character in a given string – In this article, we will brief in on the multiple methods to find the first occurrence of a character in a given string in C programming.

Suitable examples and sample programs have also been added so that you can understand the whole thing very clearly. The compiler has also been added with which you can execute it yourself.

The methods used in this piece are as follows:

  • Using Standard Model
  • Using Function
  • Using Recursion

A string is nothing but an array of characters. The value of a string is determined by the terminating character. Its value is considered to be 0.

As you can see with this example, you need to enter a string first up.

The string entered here is “Be yourself; everyone else is already taken”.

After that, you need to specify which character you need to search in the given string.

The character that is searched here is ‘s’.

Hence, after checking, it is confirmed that ‘s’ comes at the 7th spot in the string.

Thus, doing the same in C programming is as follows:

Using Standard Method

  1. Read the entered string using gets(s) and read the character to be searched using getchar() function and store the char into the variable c.

2) For loop iterates through string with the structure for(i=0;s[i];i++)

Compare the character c with s[i]

If character c matches with s[i] then initialize k=1 and come out of the loop.

3) If k=1 then print the character first occurrence at the location i.

If k!=1 then print the character is not in the string.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

#include <stdio.h>

#include <string.h>

int main()

{

    char s[1000],c;  

    int i,n,k=0;

    printf(«Enter  the string : «);

    gets(s);

    printf(«Enter character to be searched: «);

    c=getchar();

    for(i=0;s[i];i++)  

    {

     if(s[i]==c)

     {

  k=1;

       break;

}

}

    if(k)

    printf(«character  %c  is first occurrence at location:%d «,c,i);

    else

        printf(«character is not in the string «);

    return 0;

}

Output:

Enter  the string: Be yourself; everyone else is already taken

Enter character to be searched: s

character  s  is first occurrence at location:7

Using Function

  1. The main() function calls the check() function by passing string and char as arguments to the function.

2) The function compares the char c with the elements of the string using for loop for(i=0;s[i];i++).

a) If c match with s[i] then initialize k=1 and break the loop.

b) If k=1 then the function returns i value otherwise return -1. The variable i indicates the first occurrence location of the character in the string.

3) The returned value initialized to n. The main() prints the first occurrence of the character in the given string.

If n>-1 then the main() function prints the first occurrence of the character in the given string otherwise it prints the character is not in the string.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

  #include <stdio.h>

#include <string.h>

int check(char *s,char c)

{

    int i,k=0;

      for(i=0;s[i];i++)  

    {

     if(s[i]==c)

     {

  k=1;

       break;

}

}

   if(k)

   return i;

   else

   return 1;

}

int main()

{

   char s[1000],c;  

    int n;

    printf(«Enter  the string : «);

    gets(s);

    printf(«Enter character to be searched: «);

    c=getchar();

    n=check(s,c);

    if(n>1)

    printf(«character  %c  is first occurrence at location:%d «,c,n);

    else

        printf(«character is not in the string «);

    return 0;

}

Output:

Enter  the string: Be yourself; everyone else is already taken

Enter character to be searched: d

character  d  is first occurrence at location:35

Using Recursion

  1. The function check(char *s,char c)

a) Returns -1 if there is no character has existed at s[i].

b) If s[i] existed then

Compare s[i] with the character c. If both are equal then return i value.

else increase the i value and then call the function itself.

The function calls itself recursively until the character to be searched is equal to one of the characters of the string.

2) If the returned value is >-1 then print the location of the character where it occurs first in the string. Otherwise, print the character is not available in the string.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

#include <stdio.h>

#include <string.h>

int check(char *s,char c)

{

    static int i;

    if(!s[i])

    {

        return 1;

}

else

{

if(s[i]==c)

return i;

i++;

check(s,c);

}

}

int main()

{

    char s[1000],c;  

    int n;

    printf(«Enter  the string : «);

    gets(s);

    printf(«Enter character to be searched: «);

    c=getchar();

    n=check(s,c);

    if(n>1)

    printf(«character  %c  is first occurrence at location:%d «,c,n);

    else

        printf(«character is not in the string «);

        return 0;

}

Output:

Enter  the string: welcome to cbeginners

Enter character to be searched: t

character  t  is first occurrence at location:8

String str is given which contains lowercase English letters and spaces. It may contain multiple spaces. Get the first letter of every word and return the result as a string. The result should not contain any space.

Examples: 

Input : str = "geeks for geeks"
Output : gfg

Input : str = "geeks for geeks""
Output : hc

Source: https://www.geeksforgeeks.org/amazon-interview-set-8-2/

The idea is to traverse each character of string str and maintain a boolean variable, which was initially set as true. Whenever we encounter space we set the boolean variable is true. And if we encounter any character other than space, we will check the boolean variable, if it was set as true as copy that charter to the output string and set the boolean variable as false. If the boolean variable is set false, do nothing. 

Algorithm: 

1. Traverse string str. And initialize a variable v as true.
2. If str[i] == ' '. Set v as true.
3. If str[i] != ' '. Check if v is true or not.
   a) If true, copy str[i] to output string and set v as false.
   b) If false, do nothing.

Implementation:

C++

#include<bits/stdc++.h>

using namespace std;

string firstLetterWord(string str)

{

    string result = "";

    bool v = true;

    for (int i=0; i<str.length(); i++)

    {

        if (str[i] == ' ')

            v = true;

        else if (str[i] != ' ' && v == true)

        {

            result.push_back(str[i]);

            v = false;

        }

    }

    return result;

}

int main()

{

    string str = "geeks for geeks";

    cout << firstLetterWord(str);

    return 0;

}

Java

class GFG

{

    static String firstLetterWord(String str)

    {

        String result = "";

        boolean v = true;

        for (int i = 0; i < str.length(); i++)

        {

            if (str.charAt(i) == ' ')

            {

                v = true;

            }

            else if (str.charAt(i) != ' ' && v == true)

            {

                result += (str.charAt(i));

                v = false;

            }

        }

        return result;

    }

    public static void main(String[] args)

    {

        String str = "geeks for geeks";

        System.out.println(firstLetterWord(str));

    }

}

Python 3

def firstLetterWord(str):

    result = ""

    v = True

    for i in range(len(str)):

        if (str[i] == ' '):

            v = True

        elif (str[i] != ' ' and v == True):

            result += (str[i])

            v = False

    return result

if __name__ == "__main__":

    str = "geeks for geeks"

    print(firstLetterWord(str))

C#

using System;

class GFG

{

    static String firstLetterWord(String str)

    {

        String result = "";

        bool v = true;

        for (int i = 0; i < str.Length; i++)

        {

            if (str[i] == ' ')

            {

                v = true;

            }

            else if (str[i] != ' ' && v == true)

            {

                result += (str[i]);

                v = false;

            }

        }

        return result;

    }

    public static void Main()

    {

        String str = "geeks for geeks";

        Console.WriteLine(firstLetterWord(str));

    }

}

Javascript

<script>

    function firstLetterWord(str)

    {

        let result = "";

        let v = true;

        for (let i = 0; i < str.length; i++)

        {

            if (str[i] == ' ')

            {

                v = true;

            }

            else if (str[i] != ' ' && v == true)

            {

                result += (str[i]);

                v = false;

            }

        }

        return result;

    }

    let str = "geeks for geeks";

      document.write(firstLetterWord(str));

</script>

Time Complexity: O(n)
Auxiliary space: O(1). 

Approach 1 : Reverse Iterative Approach 

This is simplest approach to to getting first letter of every word of the string. In this approach we are using reverse iterative loop to get letter of words. If particular letter ( i ) is 1st letter of word or not is can be determined by checking pervious character that is (i-1). If the pervious letter is space (‘ ‘) that means (i+1) is 1st letter then we simply add that letter to the string. Except character at 0th position. At the end we simply reverse the string and function will return string which contain 1st letter of word of the string.

C++

#include <iostream>

using namespace std;

void get(string s)

{

    string str = "", temp = "";

    for (int i = s.length() - 1; i > 0; i--) {

        if (isalpha(s[i]) && s[i - 1] == ' ') {

            temp += s[i];

        }

    }

    str += s[0];

    for (int i = temp.length() - 1; i >= 0; i--) {

        str += temp[i];

    }

    cout << str << endl;

}

int main()

{

    string str = "geeks for geeks";

    string str2 = "Code of the    Day";

    get(str);

    get(str2);

    return 0;

}

Java

public class GFG {

    public static void get(String s)

    {

        String str = "", temp = "";

        for (int i = s.length() - 1; i > 0; i--) {

            if (Character.isLetter(s.charAt(i))

                && s.charAt(i - 1) == ' ') {

                temp

                    += s.charAt(i);

            }

        }

        str += s.charAt(0);

        for (int i = temp.length() - 1; i >= 0; i--) {

            str += temp.charAt(i);

        }

        System.out.println(str);

    }

    public static void main(String[] args)

    {

        String str = "geeks for geeks";

        String str2 = "Code of the    Day";

        get(str);

        get(str2);

    }

}

Python3

def get(s):

    str = ""

    temp = ""

    for i in range(len(s)-1, 0, -1):

        if s[i].isalpha() and s[i-1] == ' ':

            temp += s[i]

    str += s[0]

    for i in range(len(temp)-1, -1, -1):

        str += temp[i]

    print(str)

str = "geeks for geeks"

str2 = "Code of the    Day"

get(str)

get(str2)

Javascript

function get(s) {

  let str = "", temp = "";

  for (let i = s.length - 1; i > 0; i--) {

    if (s[i].match(/[a-zA-Z]/) && s[i - 1] === ' ') {

      temp += s[i];

    }

  }

  str += s[0];

  for (let i = temp.length - 1; i >= 0; i--) {

    str += temp[i];

  }

  console.log(str);

}

const str = "geeks for geeks";

const str2 = "Code of the    Day";

get(str);

get(str2);

Time Complexity: O(n)
Auxiliary space: O(1). 

Approach 2: Using StringBuilder

This approach uses the StringBuilder class of Java. In this approach, we will first split the input string based on the spaces. The spaces in the strings can be matched using a regular expression. The split strings are stored in an array of strings. Then we can simply append the first character of each split string in the String Builder object.  

Implementation:

C++

#include <bits/stdc++.h>

using namespace std;

string processWords(char *input)

{

    char *p;

    vector<string> s;

    p = strtok(input, " ");

    while (p != NULL)

    {

        s.push_back(p);

        p = strtok(NULL, " ");

    }

    string charBuffer;

    for (string values : s)

        charBuffer += values[0];

    return charBuffer;

}

int main()

{

    char input[] = "geeks for geeks";

    cout << processWords(input);

    return 0;

}

Java

class GFG

{

   private static StringBuilder charBuffer = new StringBuilder();

   public static String processWords(String input)

   {

        String s[] = input.split("(\s)+");

        for(String values : s)

        {

            charBuffer.append(values.charAt(0));

        }

      return charBuffer.toString();

   }

   public static void main (String[] args)

   {

      String input = "geeks for geeks";

      System.out.println(processWords(input));

   }

}

Python3

charBuffer = []

def processWords(input):

    s = input.split(" ")

    for values in s:

        charBuffer.append(values[0])

    return charBuffer

if __name__ == '__main__':

    input = "geeks for geeks"

    print(*processWords(input), sep = "")

C#

using System;

using System.Text;

class GFG

{

private static StringBuilder charBuffer = new StringBuilder();

public static String processWords(String input)

{

        String []s = input.Split(' ');

        foreach(String values in s)

        {

            charBuffer.Append(values[0]);

        }

    return charBuffer.ToString();

}

public static void Main()

{

    String input = "geeks for geeks";

    Console.WriteLine(processWords(input));

}

}

Javascript

<script>

var charBuffer = "";

function processWords(input)

{

        var s = input.split(' ');

        s.forEach(element => {

            charBuffer+=element[0];

        });

    return charBuffer;

}

var input = "geeks for geeks";

document.write( processWords(input));

</script>

Time Complexity: O(n)
Auxiliary space: O(1). 

Another Approach: Using boundary checker, refer https://www.geeksforgeeks.org/get-first-letter-word-string-using-regex-java/

This article is contributed by Aarti_Rathi and Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.


Posted by ramses147fox 2017-03-02T05:20:35Z

Hi, i need to get the first character about «Part1″and set lowercase, so: «p»

then i want to get the first charachter about»Word» and set lowercase, so: «w»

then i want to insert «.»

my result have to be: pw.

So how can i make it ?

Powershell

$a = "Part1 Word"

i want this result:

$b = "pw."

9 Replies

  • Author Alex Wittig

    Neally


    This person is a Verified Professional

    This person is a verified professional.

    Verify your account
    to enable IT peers to see that you are a professional.

    pure capsaicin

    PowerShell Expert

    • check
      1342
      Best Answers
    • thumb_up
      3087
      Helpful Votes

    I’m terrible at this.

    This is my solution.

    Powershell

    $a = "Part1 Word"
    # user the .tolower to make it all small
    # then split on space
    $first,$last = ($a.tolower()).Split(" ")
    # put it back togetther, pick the first character in string 
    # $first and first character in string $last and add a period
    $b = $first[0]+$last[0]+"."
    $b
    # $b should be "pw."
    


    1 found this helpful
    thumb_up
    thumb_down

  • Why nit use a search and replace in Notepad+ or some other editor.

    Find Part1 and replace with p

    Find Word and replace with w

    Find PW and replace with «pw.»


    0 of 1 found this helpful
    thumb_up
    thumb_down

  • Author Alex Wittig

    Neally


    This person is a Verified Professional

    This person is a verified professional.

    Verify your account
    to enable IT peers to see that you are a professional.

    pure capsaicin

    PowerShell Expert

    • check
      1342
      Best Answers
    • thumb_up
      3087
      Helpful Votes

    chris.hone.5688 wrote:

    Why nit use a search and replace in Notepad+ or some other editor.

    Find Part1 and replace with p

    Find Word and replace with w

    Find PW and replace with «pw.»

    Wouldn’t that still leave the space in between?

    If he has to do that for dozens of strings, a script is better. ¯_(ツ)_/¯


    1 found this helpful
    thumb_up
    thumb_down

  • Neally wrote:

    I’m terrible at this.

    This is my solution.

    Powershell

    $a = "Part1 Word"
    # user the .tolower to make it all small
    # then split on space
    $first,$last = ($a.tolower()).Split(" ")
    # put it back togetther, pick the first character in string 
    # $first and first character in string $last and add a period
    $b = $first[0]+$last[0]+"."
    $b
    # $b should be "pw."
    

    This is the route i’d go down. Make all lower. Split by » «. Take the two words after the split first letter.


    Was this post helpful?
    thumb_up
    thumb_down

  • Author Alex Wittig

    Neally


    This person is a Verified Professional

    This person is a verified professional.

    Verify your account
    to enable IT peers to see that you are a professional.

    pure capsaicin

    PowerShell Expert

    • check
      1342
      Best Answers
    • thumb_up
      3087
      Helpful Votes

    JitenSh wrote:

    one liner

    Text

    $a = "Part1 Word"
    $a = $a.Replace("Part1 Word", "pw.") 
    Write-host "$a" -f Green
    

     

    But that’s kind of cheating :P:P


    Was this post helpful?
    thumb_up
    thumb_down

  • Author ramses 147

    Hi guys, the problem is that $a = «Part1 Word» is an example, in that variable there may be any value, so I need to dynamically extract the first cartattere the first word lower case setting it, remove the space between the first and the second word, extract the first character of the second word by setting it lower case, and finally put a period at the end.


    Was this post helpful?
    thumb_up
    thumb_down

  • Author ramses 147

    Nelly’s script works, but i ask for the last problem:

    is it possible adding a check if $a contains MORE than 1 word do:

    Powershell

    if $a = "Word1 Word2"
    
    $first,$last = ($a.tolower()).Split(" ") 
    
    $b = $first[0]+$last[0]+"." $b 
    

    if there is only a Word do:

    Powershell

    if $a = "Word1"
    $b = $a.tolower()
    


    Was this post helpful?
    thumb_up
    thumb_down

  • To get the best help with this issue, which is complicated enough as is, we need an example of the exact text you would be searching through.


    Was this post helpful?
    thumb_up
    thumb_down

  • Author ramses 147

    I found it

    Thanks Neally  !

    Powershell

    $first,$last = ($textBox1.Text.tolower()).Split(" ")
    
    if ($last -ne $null ){ $textBox5.Text = $first[0] + $last[0] + "." + $textBox2.Text.ToLower() }
    
    else {$textBox5.Text = $first[0] + "." + $textBox2.Text.ToLower()
    


    0 of 1 found this helpful
    thumb_up
    thumb_down

Home »
C programs »
C string programs

In this program, we will learn how to capitalize each word of input string using C program?

This program will read a string and print Capitalize string, Capitalize string is a string in which first character of each word is in Uppercase (Capital) and other alphabets (characters) are in Lowercase (Small).

For example:
If input string is «hello friends how are you?» then output (in Capitalize form) will be «Hello Friends How Are You?».

Program to capitalize first character of each word in a string in C

#include <stdio.h>
#define MAX 100

int main()
{
	char str[MAX]={0};	
	int i;
	
	//input string
	printf("Enter a string: ");
	scanf("%[^n]s",str); //read string with spaces
	
	//capitalize first character of words
	for(i=0; str[i]!=''; i++)
	{
		//check first character is lowercase alphabet
		if(i==0)
		{
			if((str[i]>='a' && str[i]<='z'))
				str[i]=str[i]-32; //subtract 32 to make it capital
			continue; //continue to the loop
		}
		if(str[i]==' ')//check space
		{
			//if space is found, check next character
			++i;
			//check next character is lowercase alphabet
			if(str[i]>='a' && str[i]<='z')
			{
				str[i]=str[i]-32; //subtract 32 to make it capital
				continue; //continue to the loop
			}
		}
		else
		{
			//all other uppercase characters should be in lowercase
			if(str[i]>='A' && str[i]<='Z')
				str[i]=str[i]+32; //subtract 32 to make it small/lowercase
		}
	}
	
	printf("Capitalize string is: %sn",str);
	
	return 0;
}

Output

First run:
Enter a string: HELLO FRIENDS HOW ARE YOU?
Capitalize string is: Hello Friends How Are You?

Second run:
Enter a string: hello friends how are you?
Capitalize string is: Hello Friends How Are You?

Third run:
Enter a string: 10 ways to learn programming.
Capitalize string is: 10 Ways To Learn Programming.

C String Programs »


Понравилась статья? Поделить с друзьями:
  • Enter space in excel
  • Enter setting in word
  • Enter in the excel cell
  • Enter in one excel cell
  • Enter in excel tab