How to get value from a String before a special character

4

Hello, good morning. I'm having a little question, how can I get the value of a String before some special character. For example, Clinica Antonio S / S. I would just take the Clinica Antonio S, what comes after the bar does not need to be picked up. Can anyone help? Thanks.

    
asked by anonymous 20.04.2015 / 16:51

4 answers

6

You can do this as follows:

//String a ser analisada
String Str = new String("Clinica Antonio S/S");
//Posição do caracter na string
int pos = Str.indexOf("/");
//Substring iniciando em 0 até posição do caracter especial
System.out.println(Str.substring(0, pos) );

See an example Ideone

    
20.04.2015 / 17:19
5

You can use the StringTokenizer function contained in java.lang.Object

For example:

public class Demonstracao{
   public static void main(String[] args){
      // Cria um StringTokenizer passando como parâmetro a sua string
      StringTokenizer st = new StringTokenizer("Ola/Mundo");

      // Verifica o próximo token
      System.out.println("Proximo token: " + st.nextToken("/"));
      System.out.println("Proximo token: " + st.nextToken("/"));
   }    
}

In this case the output would be:

Proximo token: Ola
Proximo token: Mundo
    
20.04.2015 / 18:21
0

One of the ways to do it in Javascript is as follows:

<script>
 function myFunction() {
     var str = "E ai mané.Tudo bem?";
     var n = str.search(/á|é|í|ó|ú|(|)/); ///coloque aqui todos os caracteres especiais
     var a = str.substr(0,n); /// var a = 'E ai man'
 }
</script>

In other programming languages, just follow the same logic.

    
20.04.2015 / 17:20
0
var s = "Clinica Antonio S/S"

s.split(/[^\w\s]]/,1)
    
20.04.2015 / 17:31